spring boot OAuth2 role based authorization

江枫思渺然 提交于 2019-12-05 04:51:11

In the resource server you should extend the ResourceServerConfigurerAdapter to configure the requestMatchers and set the role for each resource.

@Configuration
@EnableResourceServer
public class OAuth2Config extends ResourceServerConfigurerAdapter {

    @Value("${keys.public}")
    private String publicKey;

    @Override
    public void configure(HttpSecurity http) throws Exception {
        http
                .requestMatchers()
                .antMatchers("/**")
                .and()
                .authorizeRequests()
                .antMatchers("/service1/**").access("#oauth2.hasScope('ADMIN')")
                .antMatchers("/service2/**").access("#oauth2.hasScope('USER')");
    }

    @Override
    public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
        resources.tokenStore(tokenStore());
    }

    @Bean
    public TokenStore tokenStore() {
        return new JwtTokenStore(jwtAccessTokenConverter());
    }

    @Bean
    public JwtAccessTokenConverter jwtAccessTokenConverter() {
        JwtAccessTokenConverter tokenConverter = new JwtAccessTokenConverter();
        tokenConverter.setVerifierKey(publicKey);
        return tokenConverter;
    }
}

You have received a token from the auth server. You can now use that token to make another request to the auth server to retrieve the user object. This json object would contain roles(authority). The request would look like as follows.

    curl -H "Authorization: Bearer 2a953581-e9c9-4278-b42e-8af925f49a99"  
    http://localhost:9999/uaa/user

In order to do this, you need to create user service endpoint and implement UserDetailsService also.

    @RequestMapping("/user")
public Principal user(Principal user) {
    return user;
}
    @Bean
     UserDetailsService userDetailsService.....

The role list is created and set in the org.springframework.security.core.userdetailsin the UserDetailsService.User as follows.

AuthorityUtils.createAuthorityList("ROLE_USER", "ROLE_ADMIN"));
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!