当前位置:   article > 正文

spring security oauth2 github 用户权限(GrantedAuthoritiesMapper)_set authorities

set authorities

spring security oauth2 github 用户权限(GrantedAuthoritiesMapper)

 

应用:为三方授权用户设置自定义的权限

 

 

*****************************

相关类及接口

 

*********************

默认权限设置

 

DefaultOAuth2UserService:获取用户信息的默认实现类,同时为三方用户添加权限

  1. public class DefaultOAuth2UserService implements OAuth2UserService<OAuth2UserRequest, OAuth2User> {
  2. private static final String MISSING_USER_INFO_URI_ERROR_CODE = "missing_user_info_uri";
  3. private static final String MISSING_USER_NAME_ATTRIBUTE_ERROR_CODE = "missing_user_name_attribute";
  4. private static final String INVALID_USER_INFO_RESPONSE_ERROR_CODE = "invalid_user_info_response";
  5. private static final ParameterizedTypeReference<Map<String, Object>> PARAMETERIZED_RESPONSE_TYPE = new ParameterizedTypeReference<Map<String, Object>>() {
  6. };
  7. private Converter<OAuth2UserRequest, RequestEntity<?>> requestEntityConverter = new OAuth2UserRequestEntityConverter();
  8. private RestOperations restOperations;
  9. public DefaultOAuth2UserService() {
  10. RestTemplate restTemplate = new RestTemplate();
  11. restTemplate.setErrorHandler(new OAuth2ErrorResponseErrorHandler());
  12. this.restOperations = restTemplate;
  13. }
  14. public OAuth2User loadUser(OAuth2UserRequest userRequest) throws OAuth2AuthenticationException {
  15. Assert.notNull(userRequest, "userRequest cannot be null");
  16. if (!StringUtils.hasText(userRequest.getClientRegistration().getProviderDetails().getUserInfoEndpoint().getUri())) {
  17. OAuth2Error oauth2Error = new OAuth2Error("missing_user_info_uri", "Missing required UserInfo Uri in UserInfoEndpoint for Client Registration: " + userRequest.getClientRegistration().getRegistrationId(), (String)null);
  18. throw new OAuth2AuthenticationException(oauth2Error, oauth2Error.toString());
  19. } else {
  20. String userNameAttributeName = userRequest.getClientRegistration().getProviderDetails().getUserInfoEndpoint().getUserNameAttributeName();
  21. if (!StringUtils.hasText(userNameAttributeName)) {
  22. OAuth2Error oauth2Error = new OAuth2Error("missing_user_name_attribute", "Missing required \"user name\" attribute name in UserInfoEndpoint for Client Registration: " + userRequest.getClientRegistration().getRegistrationId(), (String)null);
  23. throw new OAuth2AuthenticationException(oauth2Error, oauth2Error.toString());
  24. } else {
  25. RequestEntity request = (RequestEntity)this.requestEntityConverter.convert(userRequest);
  26. ResponseEntity response;
  27. OAuth2Error oauth2Error;
  28. try {
  29. response = this.restOperations.exchange(request, PARAMETERIZED_RESPONSE_TYPE);
  30. } catch (OAuth2AuthorizationException var10) {
  31. oauth2Error = var10.getError();
  32. StringBuilder errorDetails = new StringBuilder();
  33. errorDetails.append("Error details: [");
  34. errorDetails.append("UserInfo Uri: ").append(userRequest.getClientRegistration().getProviderDetails().getUserInfoEndpoint().getUri());
  35. errorDetails.append(", Error Code: ").append(oauth2Error.getErrorCode());
  36. if (oauth2Error.getDescription() != null) {
  37. errorDetails.append(", Error Description: ").append(oauth2Error.getDescription());
  38. }
  39. errorDetails.append("]");
  40. oauth2Error = new OAuth2Error("invalid_user_info_response", "An error occurred while attempting to retrieve the UserInfo Resource: " + errorDetails.toString(), (String)null);
  41. throw new OAuth2AuthenticationException(oauth2Error, oauth2Error.toString(), var10);
  42. } catch (RestClientException var11) {
  43. oauth2Error = new OAuth2Error("invalid_user_info_response", "An error occurred while attempting to retrieve the UserInfo Resource: " + var11.getMessage(), (String)null);
  44. throw new OAuth2AuthenticationException(oauth2Error, oauth2Error.toString(), var11);
  45. }
  46. Map<String, Object> userAttributes = (Map)response.getBody();
  47. Set<GrantedAuthority> authorities = new LinkedHashSet();
  48. authorities.add(new OAuth2UserAuthority(userAttributes)); //为用户设置默认的权限
  49. OAuth2AccessToken token = userRequest.getAccessToken();
  50. Iterator var8 = token.getScopes().iterator();
  51. while(var8.hasNext()) {
  52. String authority = (String)var8.next();
  53. authorities.add(new SimpleGrantedAuthority("SCOPE_" + authority));
  54. } //遍历用户scope,添加前缀为SCOPE_的权限
  55. return new DefaultOAuth2User(authorities, userAttributes, userNameAttributeName);
  56. }
  57. }
  58. }
  59. public final void setRequestEntityConverter(Converter<OAuth2UserRequest, RequestEntity<?>> requestEntityConverter) {
  60. Assert.notNull(requestEntityConverter, "requestEntityConverter cannot be null");
  61. this.requestEntityConverter = requestEntityConverter;
  62. }
  63. public final void setRestOperations(RestOperations restOperations) {
  64. Assert.notNull(restOperations, "restOperations cannot be null");
  65. this.restOperations = restOperations;
  66. }
  67. }

 

OAuth2UserAuthority:用户权限类

  1. public class OAuth2UserAuthority implements GrantedAuthority {
  2. private static final long serialVersionUID = 520L;
  3. private final String authority;
  4. private final Map<String, Object> attributes;
  5. public OAuth2UserAuthority(Map<String, Object> attributes) {
  6. this("ROLE_USER", attributes);
  7. } //authority的值默认为ROLE_USER
  8. public OAuth2UserAuthority(String authority, Map<String, Object> attributes) {
  9. Assert.hasText(authority, "authority cannot be empty");
  10. Assert.notEmpty(attributes, "attributes cannot be empty");
  11. this.authority = authority;
  12. this.attributes = Collections.unmodifiableMap(new LinkedHashMap(attributes));
  13. }
  14. public String getAuthority() {
  15. public Map<String, Object> getAttributes() {
  16. public boolean equals(Object obj) {
  17. public int hashCode() {
  18. public String toString() {
  19. return this.getAuthority();
  20. }
  21. }

 

*********************

自定义用户权限

 

GrantedAuthoritiesMapper:自定义权限类接口

  1. public interface GrantedAuthoritiesMapper {
  2. Collection<? extends GrantedAuthority> mapAuthorities(Collection<? extends GrantedAuthority> var1);
  3. }

 

 

*****************************

示例

 

*********************

controller 层

 

HelloController

  1. @RestController
  2. public class HelloController {
  3. @RequestMapping("/hello")
  4. public String hello(Principal principal){
  5. System.out.println(principal.toString());
  6. return "hello "+principal.getName();
  7. }
  8. @RequestMapping("/")
  9. public String redirect(){
  10. return "redirect";
  11. }
  12. }

 

*********************

默认权限

 

WebSecurityConfig

  1. @Configuration
  2. public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
  3. @Resource
  4. private UserService userService;
  5. @Bean
  6. public PasswordEncoder initPasswordEncoder(){
  7. return new BCryptPasswordEncoder();
  8. }
  9. @Override
  10. protected void configure(HttpSecurity http) throws Exception {
  11. http.formLogin().loginPage("/login/github").loginProcessingUrl("/login/form")
  12. .and()
  13. .authorizeRequests()
  14. .antMatchers("/hello").hasAnyAuthority("ROLE_USER")
  15. .antMatchers("/**").permitAll()
  16. .and()
  17. .logout().deleteCookies("JSESSIONID")
  18. .logoutSuccessUrl("/").permitAll();
  19. http.oauth2Login().loginPage("/login/github");
  20. }
  21. @Override
  22. protected void configure(AuthenticationManagerBuilder auth) throws Exception {
  23. auth.userDetailsService(userService).passwordEncoder(initPasswordEncoder());
  24. }
  25. }

 

通过权限认证后控制台输出

  1. org.springframework.security.oauth2.client.authentication.OAuth2AuthenticationToken@c8e5585:
  2. Principal: Name: [41827785], Granted Authorities: [[ROLE_USER, SCOPE_read:user]], User Attributes: [{login=lihu12344, id=41827785, node_id=MDQ6VXNlcjQxODI3Nzg1, avatar_url=https://avatars3.githubusercontent.com/u/41827785?v=4, gravatar_id=, url=https://api.github.com/users/lihu12344, html_url=https://github.com/lihu12344, followers_url=https://api.github.com/users/lihu12344/followers, following_url=https://api.github.com/users/lihu12344/following{/other_user}, gists_url=https://api.github.com/users/lihu12344/gists{/gist_id}, starred_url=https://api.github.com/users/lihu12344/starred{/owner}{/repo}, subscriptions_url=https://api.github.com/users/lihu12344/subscriptions, organizations_url=https://api.github.com/users/lihu12344/orgs, repos_url=https://api.github.com/users/lihu12344/repos, events_url=https://api.github.com/users/lihu12344/events{/privacy}, received_events_url=https://api.github.com/users/lihu12344/received_events, type=User, site_admin=false, name=null, company=null, blog=, location=null, email=null, hireable=null, bio=null, public_repos=83, public_gists=0, followers=0, following=0, created_at=2018-07-28T11:56:10Z, updated_at=2020-05-15T00:53:27Z, private_gists=0, total_private_repos=0, owned_private_repos=0, disk_usage=4269, collaborators=0, two_factor_authentication=false, plan={name=free, space=976562499, collaborators=0, private_repos=10000}}];
  3. Credentials: [PROTECTED];
  4. Authenticated: true;
  5. Details: org.springframework.security.web.authentication.WebAuthenticationDetails@fffd3270: RemoteIpAddress: 0:0:0:0:0:0:0:1;
  6. SessionId: D4C6C91511D3A2717BC5EE8CBB539BFB;
  7. Granted Authorities: ROLE_USER, SCOPE_read:user

 

 

*********************

自定义OAuth2User权限

 

GithubOAuth2User

  1. public class GithubOAuth2User implements OAuth2User {
  2. private String id;
  3. private String login;
  4. private String email;
  5. private List<GrantedAuthority> authorities= AuthorityUtils.createAuthorityList("ROLE_USER");
  6. private Map<String,Object> attributes;
  7. @Override
  8. public List<GrantedAuthority> getAuthorities() {
  9. return authorities;
  10. }
  11. @Override
  12. public Map<String, Object> getAttributes() {
  13. if (attributes==null){
  14. attributes=new HashMap<>();
  15. attributes.put("id",this.getId());
  16. attributes.put("name",this.getName());
  17. attributes.put("login",this.getLogin());
  18. attributes.put("email",this.getEmail());
  19. }
  20. return attributes;
  21. }
  22. public String getId() {
  23. public void setId(String id) {
  24. @Override
  25. public String getName() {
  26. return this.id;
  27. }
  28. public String getLogin() {
  29. public void setLogin(String login) {
  30. public String getEmail() {
  31. public void setEmail(String email) {
  32. @Override
  33. public boolean equals(Object o) {
  34. @Override
  35. public int hashCode() {
  36. @Override
  37. public String toString() {

 

WebSecurityConfig

  1. @Configuration
  2. public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
  3. @Resource
  4. private UserService userService;
  5. @Bean
  6. public PasswordEncoder initPasswordEncoder(){
  7. return new BCryptPasswordEncoder();
  8. }
  9. @Override
  10. protected void configure(HttpSecurity http) throws Exception {
  11. http.formLogin().loginPage("/login/github").loginProcessingUrl("/login/form")
  12. .and()
  13. .authorizeRequests()
  14. .antMatchers("/hello").hasAnyAuthority("ROLE_USER")
  15. .antMatchers("/**").permitAll()
  16. .and()
  17. .logout().deleteCookies("JSESSIONID")
  18. .logoutSuccessUrl("/").permitAll();
  19. http.oauth2Login().loginPage("/login/github")
  20. .userInfoEndpoint().customUserType(GithubOAuth2User.class,"github");
  21. }
  22. @Override
  23. protected void configure(AuthenticationManagerBuilder auth) throws Exception {
  24. auth.userDetailsService(userService).passwordEncoder(initPasswordEncoder());
  25. }
  26. }

 

通过认证后控制台输出

  1. org.springframework.security.oauth2.client.authentication.OAuth2AuthenticationToken@e402384d:
  2. Principal: GithubOAuth2User{id='41827785', login='lihu12344', email='null', authorities=[ROLE_USER], attributes={name=41827785, id=41827785, login=lihu12344, email=null}};
  3. Credentials: [PROTECTED];
  4. Authenticated: true;
  5. Details: org.springframework.security.web.authentication.WebAuthenticationDetails@fffc7f0c: RemoteIpAddress: 0:0:0:0:0:0:0:1;
  6. SessionId: 6C7A7C9AD0275652B4B8286F7BCEE53F;
  7. Granted Authorities: ROLE_USER

说明:默认权限为自定义的用户权限ROLE_USER

 

 

*********************

自定义权限

 

WebSecurityConfig

  1. @Configuration
  2. public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
  3. @Resource
  4. private UserService userService;
  5. @Bean
  6. public PasswordEncoder initPasswordEncoder(){
  7. return new BCryptPasswordEncoder();
  8. }
  9. @Override
  10. protected void configure(HttpSecurity http) throws Exception {
  11. http.formLogin().loginPage("/login/github").loginProcessingUrl("/login/form")
  12. .and()
  13. .authorizeRequests()
  14. .antMatchers("/hello").hasAnyAuthority("ROLE_USER")
  15. .antMatchers("/**").permitAll()
  16. .and()
  17. .logout().deleteCookies("JSESSIONID")
  18. .logoutSuccessUrl("/").permitAll();
  19. http.oauth2Login().loginPage("/login/github")
  20. .userInfoEndpoint().customUserType(GithubOAuth2User.class,"github");
  21. }
  22. @Override
  23. protected void configure(AuthenticationManagerBuilder auth) throws Exception {
  24. auth.userDetailsService(userService).passwordEncoder(initPasswordEncoder());
  25. }
  26. @Bean
  27. public GrantedAuthoritiesMapper initGrantedAuthoritiesMapper(){
  28. return collection -> {
  29. Set<GrantedAuthority> authorities=new HashSet<>();
  30. authorities.add(new SimpleGrantedAuthority("ROLE_USER"));
  31. authorities.add(new SimpleGrantedAuthority("ROLE_ADMIN"));
  32. return authorities;
  33. };
  34. }
  35. }

 

通过认证后控制台输出

  1. org.springframework.security.oauth2.client.authentication.OAuth2AuthenticationToken@5b5d3dfb:
  2. Principal: GithubOAuth2User{id='41827785', login='lihu12344', email='null', authorities=[ROLE_USER], attributes={name=41827785, id=41827785, login=lihu12344, email=null}};
  3. Credentials: [PROTECTED];
  4. Authenticated: true;
  5. Details: org.springframework.security.web.authentication.WebAuthenticationDetails@ffff4c9c: RemoteIpAddress: 0:0:0:0:0:0:0:1;
  6. SessionId: 8CF27F8FB80EBC68844C00764E0ECD4E;
  7. Granted Authorities: ROLE_USER, ROLE_ADMIN

说明:使用自定义的权限ROLE_USER、ROLE_ADMIN

 

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/正经夜光杯/article/detail/765904
推荐阅读
相关标签
  

闽ICP备14008679号