![](/img/trans.png)
[英]Setup Spring security to redirect user to login page if not authenticated
[英]Spring security : remember user who are already authenticated and don't redirect them to login form
我正在做一個項目,並試圖在我的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>
如果您使用的是Spring安全性,那么為什么不讓Spring只為您處理更可靠,更高效的一切,請使用Spring Security表單提交該表單,它將為您處理一切。
當我們已經有預定義的方法來執行此操作時,手動執行操作就沒有意義。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.