在 Spring Boot 项目中,我想绕过一些“魔法”令牌的身份验证。例如,我得到一个请求头参数Authorization:Bearer abcdef-xyz。如果这不是有效的访问令牌,我将检查我的预定义令牌。如果其中之一匹配,我将为安全上下文创建一个虚拟用户,并允许请求继续进行。
我找到了一种方法来实现这一点。
如果通过验证,则您可以创建一个虚拟身份验证并调用storeAccessToken方法
public OAuth2AccessToken readAccessToken(String tokenValue) {
Pattern pattern = Pattern.compile(HRN_REGEX);
Matcher matcher = pattern.matcher(tokenValue);
OAuth2AccessToken oAuth2AccessToken = super.readAccessToken(tokenValue);
if (oAuth2AccessToken == null && matcher.find()) {
String group = matcher.group();
String companyStr = group.replace(LICENCE_TOKEN_PREFIX, "");
Long companyId= Long.valueOf(companyStr);
boolean isCompanyValid = mLoginUserService.validateCompanyIdForAnonymousLogin(companyId);
if (isCompanyValid) {
OAuth2Request storedReq = new OAuth2Request(generateDummyReqParameters(), CLIENT, null, true, generateScope(), generateResourceIds(), null, null, null);
Authentication userAuth = new AnonymousAuthenticationToken(companyStr, companyId, AuthorityUtils.createAuthorityList(ROLE_COMPANY));
OAuth2Authentication authentication = new OAuth2Authentication(storedReq, userAuth);
storeAccessToken(new DefaultOAuth2AccessToken(tokenValue), authentication);
return new DefaultOAuth2AccessToken(tokenValue);
} else {
throw new InvalidTokenException(COMPANY_IS_NOT_LICENCED);
}
}
return oAuth2AccessToken;}
给这个身份验证一个角色(在我的例子中是“ ROLE_COMPANY ”)
在您的 ResourceServerConfigurerAdapter 类中覆盖configure(HttpSecurity http)方法并将此角色赋予相关端点
public void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/tools/validate/**").hasAnyAuthority(ROLE_COMPANY, ROLE_USER, ROLE_ADMIN)
.anyRequest().hasAnyAuthority(ROLE_USER, ROLE_ADMIN); }
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句