我正在研究一个项目,并试图在我的spring mvc项目中实现spring安全性。
我面临的问题是,对于“ chatbox / chatbox” URL,即使用户已通过身份验证,也会被重定向到登录表单。
我发现的是:第一次当用户点击“ / chatbox / chatbox” URL时,它将被重定向到登录页面,这按代码是显而易见的。输入用户名和密码后,执行将进入登录控制器的“登录”方法,并在执行“ redirect:/ chatBox / chatBox”行后检查凭据后,即使用户是已验证。
任何人都可以帮助我在这里我想念和做错的事情。 预先感谢。
下面是我的代码:
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable();
http.authorizeRequests()
.antMatchers("/resources/**"
,"/chatBox/chat-websocket/"
,"/chatBox/chat-websocket/**"
,"chatBox/chat-websocket/").permitAll();
http.authorizeRequests()
.antMatchers("/chatBox/chatBox")
.authenticated()
.and()
.formLogin().loginPage("/login/login").and().httpBasic();
}
在登录控制器中:
@RequestMapping("/userLogin")
public ModelAndView login(@ModelAttribute UserProfile userProfile,HttpServletRequest request) {
UserProfile loggedinUser = userService.findUserByUsername(userProfile.getUsername());
String passwordSha256Hex = org.apache.commons.codec.digest.DigestUtils.sha256Hex(userProfile.getPassword());
boolean isMatched = userService.checkCredentials(userProfile.getUsername(), passwordSha256Hex);
if(isMatched) {
HttpSession session = request.getSession();
session.setAttribute("username", userProfile.getUsername());
session.setAttribute("firstName", loggedinUser.getFirstName());
session.setAttribute("lastName",loggedinUser.getLastName());
session.setAttribute("isAdmin", loggedinUser.getIsAdmin());
return new ModelAndView("redirect:/chatBox/chatBox");
}
else {
System.out.println("credentials not matched");
return new ModelAndView("redirect:LoginAndRegister/LoginAndRegister");
}
}
Login.jsp
<form:form id="login-form" action="${userLoginUrl}" modelAttribute="userProfile" method="post" role="form" style="display: block;">
<div class="form-group">
<form:input type="text" path="username" name="username" id="username" tabindex="1" class="form-control" placeholder="Username" value=""/>
</div>
<div class="form-group">
<form:input type="password" path="password" name="password" id="password" tabindex="2" class="form-control" placeholder="Password"/>
</div>
<div>
<label id="login-message" class="text-danger"></label>
</div>
<div class="form-group">
<div class="row">
<div class="col-sm-6 col-sm-offset-3">
<input type="submit" name="login-submit" id="login-submit" tabindex="4" class="form-control btn btn-login" value="Log In">
</div>
</div>
</div>
答案 0 :(得分:1)
如果您使用的是Spring安全性,那为什么不让spring只为您处理更可靠,更高效的一切。请使用Spring安全性表单提交该表单,它将为您处理一切。
当我们已经有了预定义的方法时,手动执行操作就没有意义了。