隨筆簡(jiǎn)介
1、spring版本:4.3.2.RELEASE+spring security 版本:4.1.2.RELEASE(其它不做說(shuō)明)
2、所展示內(nèi)容全部用注解配置
3、springmvc已經(jīng)配置好,不作說(shuō)明
4、會(huì)涉及到springmvc,spel,el的東西,不熟悉的同學(xué)可以先去看一下這方面內(nèi)容,特別是springmvc
首先想一下,登陸需要什么,最簡(jiǎn)單的情況下,用戶(hù)名,密碼,然后比對(duì)數(shù)據(jù)庫(kù),如果吻合就跳轉(zhuǎn)到個(gè)人頁(yè)面,否則回到登陸頁(yè)面,并且提示用戶(hù)名密碼錯(cuò)誤。這個(gè)過(guò)程中應(yīng)該還帶有權(quán)限角色,并且貫穿整個(gè)會(huì)話。有了這個(gè)思路,我們只需要把數(shù)據(jù)庫(kù)的用戶(hù)名密碼交給spring security比對(duì),再讓security進(jìn)行相關(guān)跳轉(zhuǎn),并且讓security幫我們把權(quán)限角色和用戶(hù)名貫穿整個(gè)會(huì)話,實(shí)際上,我們只需要提供正確的用戶(hù)名和密碼,以及配置下security。
目錄
準(zhǔn)備工作
登陸頁(yè)面
個(gè)人頁(yè)面
開(kāi)始配置spring security
1.啟動(dòng)spring security
2.配置權(quán)限
3.編寫(xiě)UserDetailService
首先準(zhǔn)備數(shù)據(jù)庫(kù)表
CREATE TABLE `user` (
`username` varchar(255) NOT NULL,
`password` char(255) NOT NULL,
`roles` enum('MEMBER','MEMBER,LEADER','SUPER_ADMIN') NOT NULL DEFAULT 'MEMBER',
PRIMARY KEY (`username`),
KEY `username` (`username`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
PS:這里注意的是roles的內(nèi)容,LEADER也是MEMBER,這樣做,LEADER就擁有MEMBER的權(quán)限,當(dāng)然你也可以在應(yīng)用里面作判斷,這個(gè)后面會(huì)說(shuō)到。
登陸頁(yè)面
%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
%@ taglib prefix="sf" uri="http://www.springframework.org/tags/form"%>
html>
head>
title>登錄/title>
/head>
body>
div >
sf:form action="${pageContext.request.contextPath}/log" method="POST" commandName="user"> !-- spring表單標(biāo)簽,用于模型綁定和自動(dòng)添加隱藏的CSRF token標(biāo)簽 -->
h1 >登錄/h1>
c:if test="${error==true}">p style="color: red">錯(cuò)誤的帳號(hào)或密碼/p>/c:if> !-- 登陸失敗會(huì)顯示這句話 -->
c:if test="${logout==true}">p >已退出登錄/p>/c:if> !-- 退出登陸會(huì)顯示這句話 -->
sf:input path="username" name="user.username" placeholder="輸入帳號(hào)" />br />
sf:password path="password" name="user.password" placeholder="輸入密碼" />br />
input id="remember-me" name="remember-me" type="checkbox"/> !-- 是否記住我功能勾選框 -->
label for="remember-me">一周內(nèi)記住我/label>
input type="submit" class="sumbit" value="提交" >
/sf:form>
/div>
/body>
/html>
個(gè)人頁(yè)面
%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false"%>
%@taglib prefix="security" uri="http://www.springframework.org/security/tags" %>
%@ taglib prefix="sf" uri="http://www.springframework.org/tags/form"%>
html>
head>
title>歡迎你,security:authentication property="principal.username" var="username"/>${username}/title> !-- 登陸成功會(huì)顯示名字,這里var保存用戶(hù)名字到username變量,下面就可以通過(guò)EL獲取 -->
/head>
body>
security:authorize access="isAuthenticated()">h3>登錄成功!${username}/h3>/security:authorize> !-- 登陸成功會(huì)顯示名字 -->
security:authorize access="hasRole('MEMBER')"> !-- MENBER角色就會(huì)顯示 security:authorize標(biāo)簽里的內(nèi)容-->
p>你是MENBER/p>
/security:authorize>
security:authorize access="hasRole('LEADER')">
p>你是LEADER/p>
/security:authorize>
sf:form id="logoutForm" action="${pageContext.request.contextPath}/logout" method="post"> !-- 登出按鈕,注意這里是post,get是會(huì)登出失敗的 -->
a href="#" onclick="document.getElementById('logoutForm').submit();">注銷(xiāo)/a>
/sf:form>
/body>
/html>
開(kāi)始配置spring security
1.啟動(dòng)spring security
@Order(2)
public class WebSecurityAppInit extends AbstractSecurityWebApplicationInitializer{
}
繼承AbstractSecurityWebApplicationInitializer,spring security會(huì)自動(dòng)進(jìn)行準(zhǔn)備工作,這里@Order(2)是之前我springmvc(也是純注解配置)和spring security一起啟動(dòng)出錯(cuò),具體是什么我忘了,加這個(gè)讓security啟動(dòng)在后,可以避免這個(gè)問(wèn)題,如果不寫(xiě)@Order(2)沒(méi)有錯(cuò)就不用管。
2.配置權(quán)限
@Configuration
@EnableWebSecurity
@ComponentScan("com.chuanzhi.workspace.service.impl.*")
public class WebSecurityConfig extends WebSecurityConfigurerAdapter{
@Autowired
private UserDetailService userDetailService; //如果userDetailService沒(méi)有掃描到就加上面的@ComponentScan
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/me").hasAnyRole("MEMBER","SUPER_ADMIN")//個(gè)人首頁(yè)只允許擁有MENBER,SUPER_ADMIN角色的用戶(hù)訪問(wèn)
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/").permitAll() //這里程序默認(rèn)路徑就是登陸頁(yè)面,允許所有人進(jìn)行登陸
.loginProcessingUrl("/log") //登陸提交的處理url
.failureForwardUrl("/?error=true") //登陸失敗進(jìn)行轉(zhuǎn)發(fā),這里回到登陸頁(yè)面,參數(shù)error可以告知登陸狀態(tài)
.defaultSuccessUrl("/me") //登陸成功的url,這里去到個(gè)人首頁(yè)
.and()
.logout().logoutUrl("/logout").permitAll().logoutSuccessUrl("/?logout=true") //按順序,第一個(gè)是登出的url,security會(huì)攔截這個(gè)url進(jìn)行處理,所以登出不需要我們實(shí)現(xiàn),第二個(gè)是登出url,logout告知登陸狀態(tài)
.and()
.rememberMe()
.tokenValiditySeconds(604800) //記住我功能,cookies有限期是一周
.rememberMeParameter("remember-me") //登陸時(shí)是否激活記住我功能的參數(shù)名字,在登陸頁(yè)面有展示
.rememberMeCookieName("workspace"); //cookies的名字,登陸后可以通過(guò)瀏覽器查看cookies名字
}
@Override
public void configure(WebSecurity web) throws Exception {
super.configure(web);
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailService); //配置自定義userDetailService
}
}
3.編寫(xiě)UserDetailService
spring security提供給我們的獲取用戶(hù)信息的Service,主要給security提供驗(yàn)證用戶(hù)的信息,這里我們就可以自定義自己的需求了,我這個(gè)就是根據(jù)username從數(shù)據(jù)庫(kù)獲取該用戶(hù)的信息,然后交給security進(jìn)行后續(xù)處理
@Service(value = "userDetailService")
public class UserDetailService implements UserDetailsService {
@Autowired
private UserRepository repository;
public UserDetailService(UserRepository userRepository){
this.repository = userRepository; //用戶(hù)倉(cāng)庫(kù),這里不作說(shuō)明了
}
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
User user = repository.findUserByUsername(username);
if (user==null)
throw new UsernameNotFoundException("找不到該賬戶(hù)信息!"); //拋出異常,會(huì)根據(jù)配置跳到登錄失敗頁(yè)面
ListGrantedAuthority> list = new ArrayListGrantedAuthority>(); //GrantedAuthority是security提供的權(quán)限類(lèi),
getRoles(user,list); //獲取角色,放到list里面
org.springframework.security.core.userdetails.User auth_user = new
org.springframework.security.core.userdetails.User(user.getUsername(),user.getPassword(),list); //返回包括權(quán)限角色的User給security
return auth_user;
}
/**
* 獲取所屬角色
* @param user
* @param list
*/
public void getRoles(User user,ListGrantedAuthority> list){
for (String role:user.getRoles().split(",")) {
list.add(new SimpleGrantedAuthority("ROLE_"+role)); //權(quán)限如果前綴是ROLE_,security就會(huì)認(rèn)為這是個(gè)角色信息,而不是權(quán)限,例如ROLE_MENBER就是MENBER角色,CAN_SEND就是CAN_SEND權(quán)限
}
}
}
如果你想在記住我功能有效情況下,在下次進(jìn)入登陸頁(yè)面直接跳到個(gè)人首頁(yè)可以看一下這個(gè)控制器代碼
/**
* 登錄頁(yè)面
* @param
* @return
*/
@RequestMapping(value = "/")
public String login(Model model,User user
,@RequestParam(value = "error",required = false) boolean error
,@RequestParam(value = "logout",required = false) boolean logout,HttpServletRequest request){
model.addAttribute(user);
//如果已經(jīng)登陸跳轉(zhuǎn)到個(gè)人首頁(yè)
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if(authentication!=null
!authentication.getPrincipal().equals("anonymousUser")
authentication.isAuthenticated())
return "me";
if(error==true)
model.addAttribute("error",error);
if(logout==true)
model.addAttribute("logout",logout);
return "login";
}
結(jié)果展示:
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
您可能感興趣的文章:- Spring Security源碼解析之權(quán)限訪問(wèn)控制是如何做到的
- 話說(shuō)Spring Security權(quán)限管理(源碼詳解)
- java中自定義Spring Security權(quán)限控制管理示例(實(shí)戰(zhàn)篇)
- Spring security實(shí)現(xiàn)權(quán)限管理示例
- 關(guān)于SpringSecurity配置403權(quán)限訪問(wèn)頁(yè)面的完整代碼