gpt4 book ai didi

java - 如何从登录表单调用额外参数到 CustomAuthenticationProvider

转载 作者:行者123 更新时间:2023-11-30 03:04:07 26 4
gpt4 key购买 nike

我看过其他关于此问题的帖子,但仍然没有找到合适的答案。

我提交的表单有三个参数而不是两个。

这是我的 CustomAuthenticationProvider:

@Component
public class CustomAuthenticationProvider implements AuthenticationProvider {
private static final Logger logger = LoggerFactory.getLogger(CustomAuthenticationProvider.class);

@Override
public Authentication authenticate(Authentication auth) throws AuthenticationException {
String userName = auth.getName().trim();
String password = auth.getCredentials().toString().trim();
String companyName ;


if (userName.equals("admin") && password.equals("123456")) {
List<GrantedAuthority> grantedAuths = new ArrayList<>();
grantedAuths.add(new SimpleGrantedAuthority("ROLE_ADMIN"));
Authentication upat = new UsernamePasswordAuthenticationToken(userName, password, grantedAuths);
logger.info("{}:{}",userName,grantedAuths);
return upat;

} else {
return null;
}
}

@Override
public boolean supports(Class<?> auth) {
return (UsernamePasswordAuthenticationToken.class.isAssignableFrom(auth));
}

我想从登录表单获取额外参数来验证 CustomAuthenticationProvider 中的 companyName

如何从登录表单获取参数?

最佳答案

经过研究和对另一篇文章进行重大修改后,我通过注入(inject) AuthenticationDetailsSource 找到了解决方案和WebAuthenticationDetails 。所以我在这里分享解决方案:

首先为自定义过滤器创建新类来获取参数:

class ExtraParam extends WebAuthenticationDetails {

private static final long serialVersionUID = 1L;
private final String company;

public ExtraParam(HttpServletRequest request) {
super(request);
this.company = request.getParameter("company");
}

public String getCompanyName() {
return company;
}
}

然后创建用于注入(inject)的源类:

class ExtraParamSource implements AuthenticationDetailsSource<HttpServletRequest, ExtraParam> {

public ExtraParam buildDetails (HttpServletRequest context) {

return new ExtraParam(context);
}
}

然后,修改您的 spring security xml 以识别类和过滤器:

添加authentication-details-source-ref="ExtraParam"在你的<form-login像这样:

<form-login ... authentication-details-source-ref="ExtraParamSource"... />

不要忘记 bean :

<beans:bean id="ExtraParamSource" class="com.xxx.xxx.xxx.ExtraParamSource"/>

然后完成!就这样。要获取参数,只需使用下面的示例:

@Component
public class CustomAuthenticationProvider implements AuthenticationProvider{


@Override
public Authentication authenticate(Authentication auth) throws AuthenticationException {
String userName = auth.getName().trim();
String password = auth.getCredentials().toString().trim();
String companyName = ((ExtraParam)auth.getDetails()).getCompanyName();

....

引用文献:

1) How to pass an additional parameter with spring security login page

关于java - 如何从登录表单调用额外参数到 CustomAuthenticationProvider,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35215065/

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