gpt4 book ai didi

java - 基于 Spring Security token 的身份验证

转载 作者:IT老高 更新时间:2023-10-28 20:29:11 26 4
gpt4 key购买 nike

我有一个 rest api,我在其中使用 spring security 基本授权进行身份验证,客户端为每个请求发送用户名和密码。现在,我想实现基于 token 的身份验证,当用户首先通过身份验证时,我将在响应 header 中发送一个 token 。对于进一步的请求,客户端可以在 header 中包含该 token ,该 token 将用于对用户进行资源身份验证。我有两个身份验证提供程序 tokenAuthenticationProvider 和 daoAuthenticationProvider

@Component
public class TokenAuthenticationProvider implements AuthenticationProvider {

@Autowired
private TokenAuthentcationService service;

@Override
public Authentication authenticate(final Authentication authentication) throws AuthenticationException {

final RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
final HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest();
final String token = request.getHeader(Constants.AUTH_HEADER_NAME);
final Token tokenObj = this.service.getToken(token);
final AuthenticationToken authToken = new AuthenticationToken(tokenObj);
return authToken;
}

@Override
public boolean supports(final Class<?> authentication) {
return AuthenticationToken.class.isAssignableFrom(authentication);
}
}

在 daoAuthenticationProvider 中,我设置自定义 userDetailsS​​ervice 并通过从数据库中获取用户登录详细信息对其进行身份验证(只要使用 Authorization:Basic bGllQXBpVXNlcjogN21wXidMQjRdTURtR04pag== 作为 header 传递用户名和密码,它就可以正常工作)

但是当我使用 X-AUTH-TOKEN(即 Constants.AUTH_HEADER_NAME)在 header 中包含 token 时,不会调用 tokenAuthenticationProvider。我收到错误

{"timestamp":1487626368308,"status":401,"error":"Unauthorized","message":"Full authentication is required to access this resource","path":"/find"}

这就是我添加身份验证提供程序的方式。

    @Override
public void configure(final AuthenticationManagerBuilder auth) throws Exception {

final UsernamePasswordAuthenticationProvider daoProvider = new

UsernamePasswordAuthenticationProvider(this.service, this.passwordEncoder());
auth.authenticationProvider(this.tokenAuthenticationProvider);
auth.authenticationProvider(daoProvider);
}

请建议我如何在不损害 spring 安全性的当前行为的情况下实现基于 token 的身份验证。

最佳答案

这是我能够实现基于 token 的身份验证和基本身份验证的方法

SpringSecurityConfig.java

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter
{

@Override
public void configure(final AuthenticationManagerBuilder auth) throws Exception
{
auth.userDetailsService(this.participantService).passwordEncoder(this.passwordEncoder());
}

@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

@Component
public 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 security,

只要基本身份验证成功,请求就会被重定向到 onSuccessfulAuthentication,我们在其中设置 token 并在响应中发送带有一些 header “header-name”的 token 。

如果为进一步的请求发送“header-name”,则请求将首先通过 TokenAuthenticationFilter,然后再尝试尝试基本身份验证。

关于java - 基于 Spring Security token 的身份验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42354138/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com