SpringBoot与SpringSecurity整合

SpringBoot与SpringSecurity整合


  • 依赖
<dependencies>
	<dependency>
		<groupId>org.springframework.bootgroupId>
		<artifactId>spring-boot-starter-webartifactId>
	dependency>
	
	<dependency>
		<groupId>org.thymeleafgroupId>
		<artifactId>thymeleaf-spring5artifactId>
	dependency>
	<dependency>
		<groupId>org.thymeleaf.extrasgroupId>
		<artifactId>thymeleaf-extras-java8timeartifactId>
	dependency>
	
	<dependency>
		<groupId>org.springframework.bootgroupId>
		<artifactId>spring-boot-starter-securityartifactId>
	dependency>
	
	<dependency>
   		<groupId>org.thymeleaf.extrasgroupId>
   		<artifactId>thymeleaf-extras-springsecurity5artifactId>
   		<version>3.0.4.RELEASEversion>
	dependency>
	<dependency>
		<groupId>org.springframework.bootgroupId>
		<artifactId>spring-boot-starter-testartifactId>
		<scope>testscope>
		<exclusions>
			<exclusion>
				<groupId>org.junit.vintagegroupId>
				<artifactId>junit-vintage-engineartifactId>
			exclusion>
		exclusions>
	dependency>
dependencies>
  • Controller:
package com.blu.controller;

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

@Controller
public class RouterController {
     

	@RequestMapping({
      "/", "/index" })
	public String index() {
     
		return "index";
	}

	@RequestMapping("/tologin")
	public String toLogin() {
     
		return "views/login";
	}

	@RequestMapping("/level1/{id}")
	public String level1(@PathVariable("id") int id) {
     
		return "views/level1/" + id;
	}

	@RequestMapping("/level2/{id}")
	public String level2(@PathVariable("id") int id) {
     
		return "views/level2/" + id;
	}

	@RequestMapping("/level3/{id}")
	public String level3(@PathVariable("id") int id) {
     
		return "views/level3/" + id;
	}
	
}
  • SecurityConfig:
package com.blu.config;

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;

@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter{
     
	
	/**
	 * 授权
	 */
	@Override
	protected void configure(HttpSecurity http) throws Exception {
     
		
		//所有人可以访问首页,功能页需要指定权限才可以访问
		http.authorizeRequests()
			.antMatchers("/").permitAll()
			.antMatchers("/level1/**").hasRole("vip1")
			.antMatchers("/level2/**").hasRole("vip2")
			.antMatchers("/level3/**").hasRole("vip3");
		
		//没有权限将默认跳转至登录页,需要开启登录的页面
		//loginPage设置跳转至登录页的请求(默认为/login)
		//usernameParameter和passwordParameter配置登录的用户名和密码参数名称,默认就是username和password
		//loginProcessingUrl配置登录请求的url,需要和表单提交的url一致
		http.formLogin().loginPage("/tologin")
						.usernameParameter("username")
						.passwordParameter("password")
						.loginProcessingUrl("/login");
		//禁用CSRF保护
		http.csrf().disable();
		//开启注销功能和注销成功后的跳转页面(默认为登录页面)
		http.logout().logoutSuccessUrl("/");
		//开启记住我功能,Cookie默认保存两周
		http.rememberMe().rememberMeParameter("remember");
		
	}
	
	/**
	 * 认证
	 */
	@Override
	protected void configure(AuthenticationManagerBuilder auth) throws Exception {
     
		
		auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
			.withUser("BLU").password(new BCryptPasswordEncoder().encode("123456")).roles("vip2","vip3")
			.and()
			.withUser("root").password(new BCryptPasswordEncoder().encode("111111")).roles("vip1","vip2","vip3")
			.and()
			.withUser("guest").password(new BCryptPasswordEncoder().encode("111222")).roles("vip1");
	}
	
}
  • index.html

<html lang="en" xmlns:th="http://www.thymeleaf.org" xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity5">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <title>首页title>
    
    <link href="https://cdn.bootcss.com/semantic-ui/2.4.1/semantic.min.css" rel="stylesheet">
    <link th:href="@{/qinjiang/css/qinstyle.css}" rel="stylesheet">
head>
<body>


<div class="ui container">

    <div class="ui segment" id="index-header-nav" th:fragment="nav-menu">
        <div class="ui secondary menu">
            <a class="item"  th:href="@{/index}">首页a>

            
            <div class="right menu">
                
   				<div sec:authorize="!isAuthenticated()">
       				<a class="item" th:href="@{/tologin}">
           				<i class="address card icon">i> 登录
       				a>
   				div>
                
   				<div sec:authorize="isAuthenticated()">
       				<a class="item">
           				<i class="address card icon">i>
          				用户名:<span sec:authentication="principal.username">span>
          				角色:<span sec:authentication="principal.authorities">span>
       				a>
   				div>
   				<div sec:authorize="isAuthenticated()">
       				<a class="item" th:href="@{/logout}">
           				<i class="address card icon">i> 注销
       				a>
   				div>
            div>
        div>
    div>

    <div class="ui segment" style="text-align: center">
        <h3>Spring Security Study by BLUh3>
    div>

    <div>
        <br>
        <div class="ui three column stackable grid">
            <div class="column" sec:authorize="hasRole('vip1')">
                <div class="ui raised segment">
                    <div class="ui">
                        <div class="content">
                            <h5 class="content">Level 1h5>
                            <hr>
                            <div><a th:href="@{/level1/1}"><i class="bullhorn icon">i> Level-1-1a>div>
                            <div><a th:href="@{/level1/2}"><i class="bullhorn icon">i> Level-1-2a>div>
                            <div><a th:href="@{/level1/3}"><i class="bullhorn icon">i> Level-1-3a>div>
                        div>
                    div>
                div>
            div>

            <div class="column" sec:authorize="hasRole('vip2')">
                <div class="ui raised segment">
                    <div class="ui">
                        <div class="content">
                            <h5 class="content">Level 2h5>
                            <hr>
                            <div><a th:href="@{/level2/1}"><i class="bullhorn icon">i> Level-2-1a>div>
                            <div><a th:href="@{/level2/2}"><i class="bullhorn icon">i> Level-2-2a>div>
                            <div><a th:href="@{/level2/3}"><i class="bullhorn icon">i> Level-2-3a>div>
                        div>
                    div>
                div>
            div>

            <div class="column" sec:authorize="hasRole('vip3')">
                <div class="ui raised segment">
                    <div class="ui">
                        <div class="content">
                            <h5 class="content">Level 3h5>
                            <hr>
                            <div><a th:href="@{/level3/1}"><i class="bullhorn icon">i> Level-3-1a>div>
                            <div><a th:href="@{/level3/2}"><i class="bullhorn icon">i> Level-3-2a>div>
                            <div><a th:href="@{/level3/3}"><i class="bullhorn icon">i> Level-3-3a>div>
                        div>
                    div>
                div>
            div>

        div>
    div>
    
div>


<script th:src="@{/qinjiang/js/jquery-3.1.1.min.js}">script>
<script th:src="@{/qinjiang/js/semantic.min.js}">script>

body>
html>
  • views/login.html

<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <title>登录title>
    
    <link href="https://cdn.bootcss.com/semantic-ui/2.4.1/semantic.min.css" rel="stylesheet">
head>
<body>


<div class="ui container">

    <div class="ui segment">

        <div style="text-align: center">
            <h1 class="header">登录h1>
        div>

        <div class="ui placeholder segment">
            <div class="ui column very relaxed stackable grid">
                <div class="column">
                    <div class="ui form">
                        <form th:action="@{/login}" method="post">
                            <div class="field">
                                <label>Usernamelabel>
                                <div class="ui left icon input">
                                    <input type="text" placeholder="Username" name="username">
                                    <i class="user icon">i>
                                div>
                            div>
                            <div class="field">
                                <label>Passwordlabel>
                                <div class="ui left icon input">
                                    <input type="password" name="password">
                                    <i class="lock icon">i>
                                div>
                            div>
                            <div class="field">
                            	<input type="checkbox" name="remember"> 记住我
                            div>
                            
                            <input type="submit" class="ui blue submit button"/>
                        form>
                    div>
                div>
            div>
        div>

        <div style="text-align: center">
            <div class="ui label">
                i>注册
            div>
            <br><br>
            <small>[email protected]small>
        div>
        <div class="ui segment" style="text-align: center">
            <h3>Spring Security Study by BLUh3>
        div>
    div>


div>

<script th:src="@{/qinjiang/js/jquery-3.1.1.min.js}">script>
<script th:src="@{/qinjiang/js/semantic.min.js}">script>

body>
html>
  • views/level1/1.html

<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <title>首页title>
    
    <link href="https://cdn.bootcss.com/semantic-ui/2.4.1/semantic.min.css" rel="stylesheet">
    <link th:href="@{/qinjiang/css/qinstyle.css}" rel="stylesheet">
head>
<body>


<div class="ui container">

    <div th:replace="~{index::nav-menu}">div>

    <div class="ui segment" style="text-align: center">
        <h3>Level-1-1h3>
    div>

div>


<script th:src="@{/qinjiang/js/jquery-3.1.1.min.js}">script>
<script th:src="@{/qinjiang/js/semantic.min.js}">script>

body>
html>
  • views/level2/1.html 等其他页面:略

运行效果:

SpringBoot与SpringSecurity整合_第1张图片
SpringBoot与SpringSecurity整合_第2张图片
SpringBoot与SpringSecurity整合_第3张图片
SpringBoot与SpringSecurity整合_第4张图片
SpringBoot与SpringSecurity整合_第5张图片
项目源码:
链接:https://pan.baidu.com/s/1L0YTuJFSmsWQdPJ3wsQT7A
提取码:BLU1

你可能感兴趣的:(SpringBoot,SpringSecurity)