spring-boot - 由其他自定义授权服务器(SpringBoot2 和 OAuth2)进行身份验证时,OAuth2 客户端主体没有 GrantedAuthorities
问题描述
我使用 Spring Boot2 作为框架,使用 Thymeleaf 作为模板引擎。
在我的授权服务器中,我将用户“admin”添加为“ROLE_ADMIN”。
但是在客户端应用程序中,当我以“管理员”身份登录并从中打印Authentication
对象时SecurityContextHolder.getContext().getAuthentication()
,Granted Authorities
属性只有“ROLE_USER”。
以下是我的授权服务器配置。
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth
.inMemoryAuthentication()
.withUser("admin").password(passwordEncoder().encode("123")).roles("USER", "ADMIN");
auth
.inMemoryAuthentication()
.withUser("user").password(passwordEncoder().encode("123")).roles("USER");
}
以下是Authentication
来自SecurityContextHolder.getContext().getAuthentication()
的日志记录代码的对象。
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
System.out.println(auth.isAuthenticated());
System.out.println(auth.getAuthorities());
System.out.println(auth.getPrincipal());
结果是
// isAuthenticated()
true
// getAuthorites()
[ROLE_USER]
// getPrincipal()
Name: [admin], Granted Authorities: [ROLE_USER], User Attributes: [authorities=[{authority=ROLE_ADMIN}, {authority=ROLE_USER}], ...
以下是我的百里香代码。
<div sec:authorize="isAuthenticated()">
Text visible only to authenticated users.
<!-- Principal name -->
Authenticated username:
<div sec:authentication="name"></div>
<div sec:authorize="hasRole('USER')">Text visible to user.</div>
<!-- i cant see this message -->
<div sec:authorize="hasRole('ADMIN')">Text visible to admin.</div>
Authenticated user roles:
<!-- print '[ROLE_USER]' only -->
<div sec:authentication="principal.authorities"></div>
</div>
<div sec:authorize="!isAuthenticated()">Text visible only to
unauthenticated users.
</div>
所以,我想Principal.UserAttributes.authorities
在百里香中访问。
我指的是OAuth2AuthenticationToken
,OAuth2User.getAttributes()
和DefaultOAuth2User.toString()
我怎样才能做到这一点?
解决方案
我解决了。
在授权服务器中,我是这样配置的。
- 授权
WebSecurityConfigurerAdapter
服务器配置
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
...
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth
.inMemoryAuthentication()
.withUser("admin").password(passwordEncoder().encode("123")).roles("USER", "ADMIN").authorities("USER", "ADMIN");
auth
.inMemoryAuthentication()
.withUser("user").password(passwordEncoder().encode("123")).roles("USER");
}
...
}
以下是我的资源服务器的/me
映射控制器
- ResourceServer
/me
映射控制器
@RestController
public class UserController {
@RequestMapping("/me")
public Principal user(Principal principal) {
return principal;
}
}
以下是我客户的WebSecurityConfigurerAdapter
配置
- 客户端
WebSecurityConfigurerAdapter
配置
@Configuration
@EnableOAuth2Client
public class WebSecurityConfigurerAdapterImpl extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf().disable()
.authorizeRequests()
.antMatchers("/", "/home", "/error", "/webjars/**", "/resources/**", "/login**").permitAll()
.anyRequest().authenticated()
.and().oauth2Login();
}
在客户的控制器中,我是这样记录的。
- 登录
Principal
客户端控制器
@GetMapping("")
public String git1() {
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
System.out.println(auth.getPrincipal());
/** Thymeleaf using this **/
Object authenticationProperty = AuthUtils.getAuthenticationProperty(auth, "principal.attributes['authorities']");
System.out.println(authenticationProperty.toString());
return VIEW_PATH + "git1";
}
以下是结果
Name: [admin], Granted Authorities: [ROLE_USER], User Attributes: [authorities=[{authority=USER}, {authority=ADMIN}], details={remoteAddress=127.0.0.1, sessionId=null, tokenValue=82a7a532-a31e-4d0a-bd83-f15a9cbea3bc, tokenType=Bearer, decodedDetails=null}, authenticated=true, userAuthentication={authorities=[{authority=USER}, {authority=ADMIN}], details=null, authenticated=true, principal=admin, credentials=N/A, name=admin}, oauth2Request={clientId=foo, scope=[read], requestParameters={client_id=foo}, resourceIds=[], authorities=[], approved=true, refresh=false, redirectUri=null, responseTypes=[], extensions={}, refreshTokenRequest=null, grantType=null}, clientOnly=false, principal=admin, credentials=, name=admin]
[{authority=USER}, {authority=ADMIN}]
如您所见,我在授权服务器中添加了“ROLE_USER”和“ROLE_ADMIN”权限。
在资源服务器的Principal
对象中授予“ROLE_ADMIN”和“ROLE_USER”。
但在客户的Principal
对象中没有授予“ROLE_ADMIN”。只有“ROLE_USER”。
并Principal.atttibutes['authorities']
有“用户”、“管理员”。
正如@Rahil Husain 所说,DefaultOAuth2UserService
该服务仅将“ROLE_USER”授予OAuth2User
对象。
首先,我CustomAuthoritiesExtractor
通过@Componenet
注释(@Bean
也)添加到客户端。
但这在我的项目中不起作用。
所以,我实现了CustomOAuth2User
and CustomOAuth2UserService
。
像这样。
CustomOAuth2User
public class CustomOAuth2User implements OAuth2User {
private List<GrantedAuthority> authorities;
private Map<String, Object> attributes;
private String name;
public CustomOAuth2User(List<GrantedAuthority> authorities, Map<String, Object> attributes) {
this.authorities = authorities;
this.attributes = attributes;
}
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
return this.authorities;
}
@Override
public Map<String, Object> getAttributes() {
if (this.attributes == null) {
this.attributes = new HashMap<>();
this.attributes.put("name", this.getName());
}
return attributes;
}
@Override
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
}
以下是CustomOAuth2UserService
CustomOAuth2UserService
public class CustomOAuth2UserService extends DefaultOAuth2UserService {
@Override
public OAuth2User loadUser(OAuth2UserRequest userRequest) throws OAuth2AuthenticationException {
OAuth2User oAuth2User = super.loadUser(userRequest);
AuthoritiesExtractor authoritiesExtractor = new CustomAuthoritiesExtractor();
List<GrantedAuthority> grantedAuthorityList = authoritiesExtractor.extractAuthorities(oAuth2User.getAttributes());
CustomOAuth2User customOAuth2User = new CustomOAuth2User(grantedAuthorityList, oAuth2User.getAttributes());
customOAuth2User.setName(oAuth2User.getName());
return customOAuth2User;
}
}
以下是我的CustomAuthoritiesExtractor
. 此类不用作@Bean
or @Component
。直接用于CustomOAuth2Service
映射CustomOAuth2User
对象的权限
CustomAuthoritiesExtractor
public class CustomAuthoritiesExtractor implements AuthoritiesExtractor {
@Override
public List<GrantedAuthority> extractAuthorities(Map<String, Object> map) {
return AuthorityUtils.commaSeparatedStringToAuthorityList(asAuthorities(map));
}
private String asAuthorities(Map<String, Object> map) {
List<String> authorities = new ArrayList<>();
List<LinkedHashMap<String, String>> authz =
(List<LinkedHashMap<String, String>>) map.get("authorities");
for (LinkedHashMap<String, String> entry : authz) {
authorities.add(entry.get("authority"));
}
return String.join(",", authorities);
}
}
最后,我将客户端的端点更改为使用我的CustomOAuth2User
和CustomOAuth2UserService
.
所以,我像这样更改了客户端的WebSecurityConfigurerAdapter
配置。
@Configuration
@EnableOAuth2Client
public class WebSecurityConfigurerAdapterImpl extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf().disable()
.authorizeRequests()
.antMatchers("/", "/home", "/error", "/webjars/**", "/resources/**", "/login**").permitAll()
.anyRequest().authenticated()
.and().oauth2Login()
/** add this config**/
.userInfoEndpoint()
.customUserType(CustomOAuth2User.class, "teemo")
.userService(this.oauth2UserService());
}
private OAuth2UserService<OAuth2UserRequest, OAuth2User> oauth2UserService() {
return new CustomOAuth2UserService();
}
下面是我的百里香叶。
- 百里香叶
<div sec:authorize="isAuthenticated()">
Text visible only to authenticated users.
Authenticated username:
<div sec:authentication="name"></div>
<div sec:authorize="hasRole('USER')">hasRole('USER')</div>
<div sec:authorize="hasRole('ROLE_USER')">hasRole('ROLE_USER')</div>
<div sec:authorize="hasRole('ADMIN')">hasRole('ADMIN')</div>
<div sec:authorize="hasRole('ROLE_ADMIN')">hasRole('ROLE_ADMIN')</div>
<!-- TRUE -->
<div sec:authorize="hasAuthority('USER')">hasAuthority('USER')</div>
<div sec:authorize="hasAuthority('ROLE_USER')">hasAuthority('ROLE_USER')</div>
<!-- TRUE -->
<div sec:authorize="hasAuthority('ADMIN')">hasAuthority('ADMIN')</div>
<div sec:authorize="hasAuthority('ROLE_ADMIN')">hasAuthority('ROLE_ADMIN')</div>
</div>
<div sec:authorize="!isAuthenticated()">Text visible only to
unauthenticated users.
</div>
结果如下。
Text visible only to authenticated users. Authenticated username:
admin
hasAuthority('USER')
hasAuthority('ADMIN')
任何像我一样挖掘的人,我希望对这个问题和答案有所帮助。
但我不知道这是事实上的标准方式。
只是..现在工作。
推荐阅读
- reactjs - onChange using Formik Validation
- android - 在 Android Studio 上获取“无法确定标签的类型”
- java - 项目从一台计算机移动到另一台计算机后 ImageIO.read() 不起作用
- c - 在C中将数字转换为二进制和十六进制
- python - How to compare two tables and identify a specific type of row to be returned?
- python - Is there some way to find the intersect in multiple file names between multiple CSV headers?
- r - How to create a stand alone legend in R
- php - mb_detect_encoding does not detect SJIS-mac?
- r - 汇总数据框时获取“未使用的参数”
- html - HTML 电子邮件 - 电子邮件中的图像仅在某些设备上显示