我看过其他有关此事的帖子,但仍未找到合适的答案。
我提交的表单有三个参数而不是两个。
这是我的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));
}
我想从登录表单中获取额外参数,以验证companyName
中的CustomAuthenticationProvider
如何从登录表单中获取参数?
答案 0 :(得分:2)
经过一项研究和其他帖子的主要修改后,我通过注入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;
}
}
然后创建注入源类:
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"... />
不要忘记豆子:
<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