Spring Securityのロールの命名規則

<

div class=”information”>Spring SecurityでDBの値によって独自にロールを付与したかったので
UserDetailsServiceImplを作って下記のような実装をしました。

public class UserDetailsServiceImpl implements UserDetailsService {
    @Autowired
    private UserRepository userRepository;
 
    @Override
    public UserDetails loadUserByUsername(String userId) throws UsernameNotFoundException {
        List<ManageUser> users = userRepository.findByUserid(userId);
        if (users.size() == 1) {
            ManageUser user = users.get(0);
            Collection<GrantedAuthority> authorityList = new ArrayList<>();
            String userType = user.getUser_type();
            String authorityLevel = user.getAuthority_level();
            if ("system".equals(userType)) {
                authorityList.add(new SimpleGrantedAuthority("SYSTEM"));
            } else if ("user".equals(userType)) {
                authorityList.add(new SimpleGrantedAuthority("USER"));
            } else {
                authorityList.add(new SimpleGrantedAuthority("REFER"));
            }
            return new User(userId, user.getPassword(), authorityList);
        } else {
            throw new UsernameNotFoundException("User is not found, The user_id is " + userId);
        }
    }

で、WebSecurityConfigurerAdapter継承したWebSecurityConfigで下記のように設定

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .authorizeRequests()
                .antMatchers("/css/**", "/img/**").permitAll()
                .antMatchers("/system/**").hasRole("SYSTEM")
                .antMatchers("/user/**").hasRole("USER")
                .antMatchers("/refer/**").hasRole("REFER")
                .anyRequest().authenticated();
    }

つまり、リクエストのURLの先頭部分で参照権限を分けたかったのです。

これでSYSTEM権限をもつユーザーでログインして/system/homeを開いてみると、404。

なんでだろうとhasRoleの中身を確認してみると、

    private static String hasRole(String role) {
        Assert.notNull(role, "role cannot be null");
        if (role.startsWith("ROLE_")) {
            throw new IllegalArgumentException("role should not start with 'ROLE_' since it is automatically inserted. Got '" + role + "'");
        }
        return "hasRole('ROLE_" + role + "')";
    }

ROLE_を先頭に付けないといけなかったんですね。

分かるかいこんなん(泣)。

確かに、リファレンスを見ると書いてありました。

Any URL that starts with “/admin/” will be resticted to users who have the role “ROLE_ADMIN”. You will notice that since we are invoking the hasRole method we do not need to specify the “ROLE_” prefix.

しかしあんまリファレンス読み込んでる時間も無いんだよなぁ…


投稿日

カテゴリー:

投稿者:

タグ:

コメント

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です

このサイトはスパムを低減するために Akismet を使っています。コメントデータの処理方法の詳細はこちらをご覧ください