我不使用 Okta,因此我不知道它是如何工作的。但我有两个假设:
- 每个请求的 Authorization 标头中都包含一个 accessToken
- 您向 ${baseUrl}/v1/introspect 发出 POST 请求,它会以 true 或 false 回答您,表明 accessToken 是否有效
考虑到这两个假设,如果我必须手动实现自定义安全逻辑身份验证,我会执行以下步骤:
- 注册并实施
CustomAuthenticationProvider
- 添加过滤器以从请求中提取访问令牌
注册自定义身份验证提供程序:
// In OktaOAuth2WebSecurityConfig.java
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.authenticationProvider(customAuthenticationProvider());
}
@Bean
CustomAuthenticationProvider customAuthenticationProvider(){
return new CustomAuthenticationProvider();
}
CustomAuthenticationProvider:
public class CustomAuthenticationProvider implements AuthenticationProvider {
private static final Logger logger = LoggerFactory.getLogger(CustomAuthenticationProvider.class);
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
logger.debug("Authenticating authenticationToken");
OktaTokenAuthenticationToken auth = (OktaTokenAuthenticationToken) authentication;
String accessToken = auth.getToken();
// You should make a POST request to ${oktaBaseUrl}/v1/introspect
// to determine if the access token is good or bad
// I just put a dummy if here
if ("ThanhLoyal".equals(accessToken)){
List<GrantedAuthority> authorities = Collections.singletonList(new SimpleGrantedAuthority("USER"));
logger.debug("Good access token");
return new UsernamePasswordAuthenticationToken(auth.getPrincipal(), "[ProtectedPassword]", authorities);
}
logger.debug("Bad access token");
return null;
}
@Override
public boolean supports(Class<?> clazz) {
return clazz == OktaTokenAuthenticationToken.class;
}
}
注册过滤器以从请求中提取accessToken:
// Still in OktaOAuth2WebSecurityConfig.java
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.addFilterAfter(accessTokenExtractorFilter(), UsernamePasswordAuthenticationFilter.class)
.authorizeRequests().anyRequest().authenticated();
// And other configurations
}
@Bean
AccessTokenExtractorFilter accessTokenExtractorFilter(){
return new AccessTokenExtractorFilter();
}
还有它自己的过滤器:
public class AccessTokenExtractorFilter extends OncePerRequestFilter {
private static final Logger logger = LoggerFactory.getLogger(AccessTokenExtractorFilter.class);
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
logger.debug("Filtering request");
Authentication authentication = getAuthentication(request);
if (authentication == null){
logger.debug("Continuing filtering process without an authentication");
filterChain.doFilter(request, response);
} else {
logger.debug("Now set authentication on the request");
SecurityContextHolder.getContext().setAuthentication(authentication);
filterChain.doFilter(request, response);
}
}
private Authentication getAuthentication(HttpServletRequest request) {
String accessToken = request.getHeader("Authorization");
if (accessToken != null){
logger.debug("An access token found in request header");
List<GrantedAuthority> authorities = Collections.singletonList(new SimpleGrantedAuthority("USER"));
return new OktaTokenAuthenticationToken(accessToken, authorities);
}
logger.debug("No access token found in request header");
return null;
}
}
我在这里上传了一个简单的项目供您参考:https://github.com/MrLoyal/spring-security-custom-authentication
它是如何工作的:
- AccessTokenExtractorFilter 位于 UsernamePasswordAuthenticationFilter 之后,这是 Spring Security 的默认过滤器
- 一个请求到达,上面的过滤器从中提取accessToken并放在SecurityContext中
- 稍后,AuthenticationManager 调用 AuthenticationProvider(s) 来验证请求。在这种情况下,调用了 CustomAuthenticationProvider
顺便说一句,您的问题应该包含spring-security 标签。
更新 1:关于 AuthenticationEntryPoint
AuthenticationEntryPoint 声明当未经身份验证的请求到达时要做什么(在我们的例子中,当请求不包含有效的“授权”标头时要做什么)。
在我的 REST API 中,我只是向客户端响应 401 HTTP 状态代码。
// CustomAuthenticationEntryPoint
@Override
public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
response.reset();
response.setStatus(401);
// A utility method to add CORS headers to the response
SecUtil.writeCorsHeaders(request, response);
}
Spring 的LoginUrlAuthenticationEntryPoint 将用户重定向到登录页面(如果已配置)。
因此,如果您想将未经身份验证的请求重定向到 Okta 的登录页面,您可以使用 AuthenticationEntryPoint。