springboot 整合spring-security

市面上大概有3種經常使用的受權和認證方法,①,shiro,②,oauth,③,spring-security;html

而spring-security 能與springboot進行無縫整合,能夠說是官方推薦,但比較複雜,shiro簡單而易用,我的也很喜歡。oauth暫時還沒接觸到java

1,配置 

①,pom.xmlweb

<parent>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-parent</artifactId>
	<version>2.0.2.RELEASE</version>
</parent>

<dependencies>
	<!-- 引入thymeleaf 的shiro命名空間 -->
	<dependency>
		<groupId>org.thymeleaf.extras</groupId>
		<artifactId>thymeleaf-extras-springsecurity4</artifactId>
	</dependency>
	<!--引入spring-security -->
	<dependency>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-security</artifactId>
	</dependency>
	<dependency>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-thymeleaf</artifactId>
	</dependency>
	<dependency>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-web</artifactId>
	</dependency>
<dependencies>

②,application.properties 配置spring

#禁用thymeleaf緩存,這樣在頁面按下ctrl+f9(從新編譯),便能實時更新頁面
spring.thymeleaf.cache=false

2,spring-security 在java代碼的配置

import org.springframework.context.annotation.Bean;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.NoOpPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    /**
     * 配置受權信息
     * @param http
     * @throws Exception
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests().antMatchers("/").permitAll()//容許訪問首頁
                    .antMatchers("/level1/*").hasRole("vip1")
                    .antMatchers("/level2/*").hasRole("vip2")
                    .antMatchers("/level3/*").hasRole("vip3");
//        自定義登陸頁面
        http.formLogin().loginPage("/userlogin")//這個/必須加上,配置登陸url
                .usernameParameter("user")//指定進行認證的參數名
                .passwordParameter("pwd");

        http.logout().logoutSuccessUrl("/");//開啓註銷功能,並配置退出成功後重定向的的url
        http.rememberMe().rememberMeParameter("remeber");//開啓記住我功能,默認會記住14天
    }

    /**
     * 配置認證規則
     * @param auth
     * @throws Exception
     */
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        //內存配置
        auth.inMemoryAuthentication()
                .withUser("xiaosu").password("123").roles("vip1")//xiaosu的角色是vip1
                .and()
                .withUser("小蘇").password("123").roles("vip2")//小蘇的角色是vip1
                .and()
                .withUser("翛蘇").password("123").roles("vip3");//翛蘇的角色是vip1
    }
    /*  若是不配置PasswordEncoder 會報以下錯誤
        java.lang.IllegalArgumentException: There is no PasswordEncoder mapped for the id "null"
    */
    @Bean
    public PasswordEncoder passwordEncoder() {
        //雖然已通過時,但這裏不對密碼進行加密
        return NoOpPasswordEncoder.getInstance();
    }
}

3,地址映射

①,controller層映射頁面地址緩存

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class SercurityController {

    @RequestMapping("level{level}/{page}")
    public ModelAndView toPage(@PathVariable("level")String level,@PathVariable("page")String page){
        ModelAndView view=new ModelAndView(String.format("pages/level%s/%s",level,page));
        return view;
    }
}

②,配置登陸以及首頁映射springboot

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class MvcConfig implements WebMvcConfigurer {
    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/").setViewName("welcome");
        registry.addViewController("/userlogin").setViewName("pages/login");
    }
}

4,頁面代碼

①,welcome.htmlcookie

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org"
	  xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity4"><!--引入thymeleaf的shiro命名空間-->
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<h1 align="center">歡迎光臨武林祕籍管理系統</h1>
<!--沒有認證信息,顯示這個-->
<div sec:authorize="!isAuthenticated()">
	<h2 align="center">遊客您好,若是想查看武林祕籍 <a th:href="@{/userlogin}">請登陸</a></h2>
</div>
<!--認證後,顯示這個-->
<div sec:authorize="isAuthenticated()">
	<!--顯示認證信息-->
	<div>您好:<span sec:authentication="name"></span>,
		<!--顯示角色信息-->
		roles: <span sec:authentication="principal.authorities"></span>
	</div>
	<!--退出連接,注意這裏必須是post請求-->
	<form th:action="@{/logout}" method="post">
		<input type="submit" value="退出">
	</form>
</div>



<hr>
<!--用戶有角色vip1 時顯示-->
<div sec:authorize="hasRole('vip1')">
	<h3>普通武功祕籍</h3>
	<ul>
		<li><a th:href="@{/level1/1}">羅漢拳</a></li>
		<li><a th:href="@{/level1/2}">武當長拳</a></li>
		<li><a th:href="@{/level1/3}">全真劍法</a></li>
	</ul>
</div>
<!--用戶有角色vip2 時顯示-->
<div sec:authorize="hasRole('vip2')">
	<h3>高級武功祕籍</h3>
	<ul>
		<li><a th:href="@{/level2/1}">太極拳</a></li>
		<li><a th:href="@{/level2/2}">七傷拳</a></li>
		<li><a th:href="@{/level2/3}">梯雲縱</a></li>
	</ul>
</div>
<!--用戶有角色vip3 時顯示-->
<div sec:authorize="hasRole('vip3')">
	<h3>絕世武功祕籍</h3>
	<ul>
		<li><a th:href="@{/level3/1}">葵花寶典</a></li>
		<li><a th:href="@{/level3/2}">龜派氣功</a></li>
		<li><a th:href="@{/level3/3}">獨孤九劍</a></li>
	</ul>
</div>


</body>
</html>

②,level2下的3.html頁面以下,其他類似app

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
	<a th:href="@{/}">返回</a>
	<h1>梯雲縱</h1>
	<p>踩本身的腳往上跳</p>
</body>
</html>

③,login.htmlide

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
	<h1 align="center">歡迎登錄武林祕籍管理系統</h1>
	<hr>
	<div align="center">
		<form th:action="@{/userlogin}" method="post">
			用戶名:<input name="user"/><br>
			密碼:<input name="pwd"><br/>
			<input type="checkbox" name="remeber"> 記住我<br/>
			<input type="submit" value="登錄">
		</form>
	</div>
</body>
</html>

5,啓動項目,進行測試

①,用xiaosu進行登陸spring-boot

②,登陸成功,顯示以下

③,在登陸時勾選記住個人話,會往cookie存儲以下信息

 

相關文章
相關標籤/搜索