我有index.jsp,它发布到`j_spring_security_check。我正在尝试将文本框值设置为Session变量。
下面是我的index.jsp
<form id="loginForm" name="loginForm" method="post" action="j_spring_security_check" autocomplete="off">
<label>email address</label>
<input type="text" name="j_username" id="username" autocorrect="off" autocapitalize="off" autocomplete="off" placeholder="email address" title="email address" />
<label>password</label>
<input type="password" name="j_password" id="password" autocorrect="off" autocapitalize="off" autocomplete="off" placeholder="password" title="password" />
<button type="submit" onclick="this.disabled=true; this.form.submit.click();"><spring:message code="v2.login.button" /></button>
</form>
我试图在Session中设置用户名值,但是表单发布到j_spring_security_check,我真的不知道Spring安全性如何工作,所以我不确定在哪里添加逻辑以将用户名值放在会话中。我想知道是否可行如果是这样我在哪里添加逻辑?
解决方案:当调用登录表单/ j_spring_security_check UsernamePasswordAuthenticationFilter以验证用户身份时。以下是将用户名置于会话中的更改 在security-applicationContext.xml
中添加了customUsernamePasswordAuthenticationFilter,如下所示<beans:bean id="customUsernamePasswordAuthenticationFilter" class="com.datacert.core.security.filter.CustomUsernamePasswordAuthenticationFilter" >
<beans:property name="authenticationManager" ref="authenticationManager" />
<beans:property name="authenticationFailureHandler" ref="DCAuthenticationFailureHandler" />
<beans:property name="authenticationSuccessHandler" ref="DCAuthenticationSuccessHandler" />
</beans:bean>
并创建了一个在会话中设置用户名的类
@Primary
public class CustomUsernamePasswordAuthenticationFilter extends UsernamePasswordAuthenticationFilter {
public CustomUsernamePasswordAuthenticationFilter() {
super();
}
@Override
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
throws AuthenticationException {
/*
* String username = super.obtainUsername(request); if (username != null && !StringUtils.isEmpty(username)) {
* HttpSession session = request.getSession(); session.setAttribute("username", username); }
*/
return super.attemptAuthentication(request, response);
}
}
答案 0 :(得分:1)
在Spring安全性中,身份验证对象保存在SecurityContext
。
要让Authentication
对象从org.springframework.security.core.context.SecurityContextHolder#getContext()
SecurityContext securityContext = SecurityContextHolder.getContext();
Object principal;
String username;
if(null != securityContext.getAuthentication()){
principal = securityContext.getAuthentication().getPrincipal();
username = securityContext.getAuthentication().getName();
}
username
的值将是身份验证中使用的用户名。
principal
的值将是主要对象。许多身份验证提供程序将创建一个UserDetails对象作为主体。