这是我能够实现基于令牌的身份验证和基本身份验证的方式
SpringSecurityConfig.java
@Configuration@EnableWebSecuritypublic class SecurityConfig extends WebSecurityConfigurerAdapter{ @Override public void configure(final AuthenticationManagerBuilder auth) throws Exception { auth.userDetailsService(this.participantService).passwordEnprer(this.passwordEnprer()); } @Override protected void configure(final HttpSecurity http) throws Exception { //Implementing Token based authentication in this filter final TokenAuthenticationFilter tokenFilter = new TokenAuthenticationFilter(); http.addFilterBefore(tokenFilter, BasicAuthenticationFilter.class); //Creating token when basic authentication is successful and the same token can be used to authenticate for further requests final CustomBasicAuthenticationFilter customBasicAuthFilter = new CustomBasicAuthenticationFilter(this.authenticationManager() ); http.addFilter(customBasicAuthFilter); }}TokenAuthenticationFilter.java
public class TokenAuthenticationFilter extends GenericFilterBean { @Override public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain) throws IOException, ServletException { final HttpServletRequest httpRequest = (HttpServletRequest)request; //extract token from header final String accessToken = httpRequest.getHeader("header-name"); if (null != accessToken) {//get and check whether token is valid ( from DB or file wherever you are storing the token) //Populate SecurityContextHolder by fetching relevant information using token final User user = new User( "username", "password", true, true, true, true, authorities); final UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(user, null, user.getAuthorities()); SecurityContextHolder.getContext().setAuthentication(authentication); } chain.doFilter(request, response); } }CustomBasicAuthenticationFilter.java
@Componentpublic class CustomBasicAuthenticationFilter extends BasicAuthenticationFilter { @Autowired public CustomBasicAuthenticationFilter(final AuthenticationManager authenticationManager) { super(authenticationManager); } @Override protected void onSuccessfulAuthentication(final javax.servlet.http.HttpServletRequest request, final javax.servlet.http.HttpServletResponse response, final Authentication authResult) { //Generate Token //Save the token for the logged in user //send token in the response response.setHeader("header-name" , "token"); }}由于我们的CustomBasicAuthenticationFilter已配置并添加为Spring安全性的过滤器,
只要基本身份验证成功,请求就会重定向到onSuccessfulAuthentication,在此我们设置令牌,并在响应中使用一些标头“ header-
name”发送它。
如果发送“ header-name”以请求进一步的请求,则该请求将在尝试尝试基本身份验证之前先通过TokenAuthenticationFilter。



