gpt4 book ai didi

Spring Security 通过 URL 进行身份验证

转载 作者:行者123 更新时间:2023-12-03 01:34:14 24 4
gpt4 key购买 nike

我有一个 Spring MVC 应用程序,它使用 Spring Security 和基于表单的登录进行授权/身份验证。

现在我想添加一个特殊的 URL,其中包含一个无需其他信息即可访问的 token ,因为该 token 对于用户来说是唯一的:

http://myserver.com/special/5f6be0c0-87d7-11e2-9e96-0800200c9a66/text.pdf

我需要如何配置 Spring Security 以使用该 token 进行用户身份验证?

最佳答案

您需要定义自定义预身份验证过滤器。

http 内的安全应用上下文中标签:

<custom-filter position="PRE_AUTH_FILTER" ref="preAuthTokenFilter" />

然后定义您的过滤器 bean(及其适当的属性):

<beans:bean class="com.yourcompany.PreAuthTokenFilter"
id="preAuthTokenFilter">
<beans:property name="authenticationDetailsSource" ref="authenticationDetailsSource" />
<beans:property name="authenticationManager" ref="authenticationManager" />
<beans:property name="authenticationEntryPoint" ref="authenticationEntryPoint"/>
</beans:bean>

创建从 GenericFilterBean 扩展的自定义过滤器

public class PreAuthTokenFilter extends GenericFilterBean {

private AuthenticationEntryPoint authenticationEntryPoint;
private AuthenticationManager authenticationManager;
private AuthenticationDetailsSource authenticationDetailsSource = new WebAuthenticationDetailsSource();

@Override
public void doFilter(ServletRequest req, ServletResponse resp,
FilterChain chain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) resp;

String token = getTokenFromHeader(request);//your method

if (StringUtils.isNotEmpty(token)) {
/* get user entity from DB by token, retrieve its username and password*/

if (isUserTokenValid(/* some args */)) {
try {
UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(username, password);
authRequest.setDetails(this.authenticationDetailsSource.buildDetails(request));
Authentication authResult = this.authenticationManager.authenticate(authRequest);
SecurityContextHolder.getContext().setAuthentication(authResult);
} catch (AuthenticationException e) {
}
}
}

chain.doFilter(request, response);
}

/*
other methods
*/

如果您不想或无法找回密码,则需要创建自己的 AbstractAuthenticationToken它将仅接收用户名作为参数(主体)并使用它而不是 UsernamePasswordAuthenticationToken :

public class PreAuthToken extends AbstractAuthenticationToken {

private final Object principal;

public PreAuthToken(Object principal) {
super(null);
super.setAuthenticated(true);
this.principal = principal;
}

@Override
public Object getCredentials() {
return "";
}

@Override
public Object getPrincipal() {
return principal;
}
}

关于Spring Security 通过 URL 进行身份验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15291357/

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