我正试着了解SpringSecurity,阅读SpringSecurity教程,我在下面遇到了这段代码。在 doFilterInternal
方法检查是否设置了授权令牌,如果未设置,则直接调用 filterChain.doFilter()
方法。如果设置了授权令牌,只需显式地将授权令牌添加到安全上下文中,然后调用 filterChain.doFilter()
. 这有什么必要?为什么要将authenticationtoken设置为 SecurityContext
明确地?
代码
package com.betterjavacode.SpringAppCache;
import io.jsonwebtoken.Jwts;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
public class AuthorizationFilter extends BasicAuthenticationFilter
{
public AuthorizationFilter(AuthenticationManager authenticationManager)
{
super(authenticationManager);
}
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
throws IOException, ServletException
{
String header = request.getHeader("Authorization");
if(header == null || !header.startsWith("Bearer"))
{
filterChain.doFilter(request,response);
return;
}
UsernamePasswordAuthenticationToken authenticationToken = getAuthentication(request);
SecurityContextHolder.getContext().setAuthentication(authenticationToken);
filterChain.doFilter(request,response);
}
private UsernamePasswordAuthenticationToken getAuthentication(HttpServletRequest request)
{
String token = request.getHeader("Authorization");
if(token != null)
{
String user = Jwts.parser().setSigningKey("SecretKeyToGenJWTs".getBytes())
.parseClaimsJws(token.replace("Bearer",""))
.getBody()
.getSubject();
if(user != null)
{
return new UsernamePasswordAuthenticationToken(user, null, new ArrayList<>());
}
return null;
}
return null;
}
}
1条答案
按热度按时间yuvru6vn1#
当您将身份验证设置为
SecurityContext
通过使用SecurityContextHolder.getContext().setAuthentication
,您可以直接将经过身份验证的主体(在计算机安全中,它只是一个可以被身份验证的实体)设置为上下文。这是非常有用的,因为您的过滤器将是一个'集中'授权。因此,当您的过滤器执行授权时,它可以将经过身份验证的用户(主体)设置为上下文,然后应用程序的其余部分可以通过上下文访问经过身份验证的用户
SecurityContextHolder
.在很多情况下,当您需要在请求生命周期的某个地方访问“已记录”的用户信息时,这非常有用。