Spring boot8之整合Spring Security

Spring boot整合Spring Security

  • 配置pom.xml

    1 <?xml version="1.0" encoding="UTF-8"?>

    2 <project xmlns="http://maven.apache.org/POM/4.0.0"

    3                   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

    4                   xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">

    5         <modelVersion>4.0.0</modelVersion>

    6 

    7         <groupId>com.wiggin</groupId>

    8         <artifactId>springbootandsecurity</artifactId>

    9         <version>1.0-SNAPSHOT</version>

   10         <parent>

   11                 <groupId>org.springframework.boot</groupId>

   12 

   13                 <artifactId>spring-boot-starter-parent</artifactId>

   14                 <version>2.1.5.RELEASE</version>

   15         </parent>

   16 

   17         <dependencies>

   18                 <dependency>

   19                         <groupId>org.springframework.boot</groupId>

   20                         <artifactId>spring-boot-starter-web</artifactId>

   21                         <version>2.1.5.RELEASE</version>

   22                 </dependency>

   23                 <dependency>

   24                         <groupId>org.springframework.boot</groupId>

   25                         <artifactId>spring-boot-starter-thymeleaf</artifactId>

   26                 </dependency>

   27                 <dependency>

   28                         <groupId>org.springframework.boot</groupId>

   29                         <artifactId>spring-boot-starter-security</artifactId>

   30                 </dependency>

   31         </dependencies>

   32 

   33 </project>

  • 创建实体类HelloHandler

    1 package com.wiggin.entity;

    2 

    3 import org.springframework.stereotype.Controller;

    4 import org.springframework.web.bind.annotation.GetMapping;

    5 

    6 @Controller

    7 public class HelloHandler {

    8         @GetMapping("/index")

    9         public String index(){

   10                 return "index";

   11         }

   12 }

  • 创建index.HTML

    1 package com.wiggin.entity;

    2 

    3 import lombok.Data;

    4 

    5 import java.io.Serializable;

    6 import java.util.Date;

    7 

    8 @Data

    9 public class Student implements Serializable {

   10         private Long id;

   11         private String name;

   12         private int score;

   13         private Date birthday;

   14 }

  • 配置application.yml(自定义登录密码和账户)

    1 spring:

    2     thymeleaf:

    3         prefix: classpath:/templates/

    4         suffix: .html

    5     security:

    6         user:

    7             name: admin

    8             password: 123456

  • 创建启动类Application

    1 package com.wiggin;

    2 

    3 import org.springframework.boot.SpringApplication;

    4 import org.springframework.boot.autoconfigure.SpringBootApplication;

    5 

    6 @SpringBootApplication

    7 public class Application {

    8         public static void main(String[] args) {

    9                 SpringApplication.run(Application.class,args);

   10         }

   11 }

权限管理

定义两个HTML资源,index.html、admin.html,同时定义两个角色ADMIN和USER,ADMIN拥有访问index.html和admin.html的权限,USER之能访问index.html。

  • 创建SecurityConfig类

    1 package com.wiggin.config;

    2 

    3 import org.springframework.context.annotation.Configuration;

    4 import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;

    5 import org.springframework.security.config.annotation.web.builders.HttpSecurity;

    6 import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;

    7 import org.springframework.security.config.annotation.web.configuration.WebSecurityConfiguration;

    8 import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

    9 

   10 @Configuration

   11 @EnableWebSecurity

   12 public class SecurityConfig extends WebSecurityConfigurerAdapter {

   13 

   14         @Override // 添加账户与角色

   15         protected void configure(AuthenticationManagerBuilder auth) throws Exception {

   16         /*

   17  withUser("user"): 用户名

   18  password(new MyPasswordEncoder().encode("123456")): 密码,自定义加密

   19  roles("USER"): 角色定位

   20  and():连接其他项

   21  */

   22                 auth.inMemoryAuthentication().passwordEncoder(new MyPasswordEncoder())

   23                                 .withUser("user").password(new MyPasswordEncoder().encode("123456")).roles("USER")

   24                                 .and()

   25                                 .withUser("admin").password(new MyPasswordEncoder().encode("456789")).roles("ADMIN","USER");

   26         }

   27 

   28         @Override // 设置角色和权限的关系

   29         protected void configure(HttpSecurity http) throws Exception {

   30         /*

   31  http.authorizeRequests().antMatchers("/admin").hasRole("ADMIN"): 授权网址权限

   32  antMatchers("index").access("hasRole('ADMIN') or hasRole('USER')"): 授权网址多权限

   33  anyRequest().authenticated() :所有的网址都需要被授权

   34  and():连接其他项

   35  formLogin().loginPage("/login") :自定义登录界面login

   36  permitAll(): 允许通过不需要权限

   37  logout().permitAll() : 退出同样不需要权限

   38  csrf().disable() csrf失效

   39  */

   40                 http.authorizeRequests().antMatchers("/admin").hasRole("ADMIN")

   41                                 .antMatchers("index").access("hasRole('ADMIN') or hasRole('USER')")

   42                                 .anyRequest().authenticated()

   43                                 .and()

   44                                 .formLogin()

   45                                 .loginPage("/login")

   46                                 .permitAll()

   47                                 .and()

   48                                 .logout()

   49                                 .permitAll()

   50                                 .and()

   51                                 .csrf()

   52                                 .disable();

   53       

  • 密码的自定义编码MyPasswordEncoder

    1 package com.wiggin.config;

    2 

    3 import org.springframework.security.crypto.password.PasswordEncoder;

    4 

    5 public class MyPasswordEncoder implements PasswordEncoder {

    6         // 实现对密码的编码

    7         @Override

    8         public String encode(CharSequence charSequence) {

    9                 return charSequence.toString();

   10         }

   11 

   12         @Override

   13         public boolean matches(CharSequence charSequence, String s) {

   14                 return s.equals(charSequence.toString());

   15         }

   16 

   17 }

  • 修改HelloHandler

    1 package com.wiggin.controller;

    2 

    3 import org.springframework.stereotype.Controller;

    4 import org.springframework.web.bind.annotation.GetMapping;

    5 

    6 @Controller

    7 public class HelloHandler {

    8         @GetMapping("/index")

    9         public String index(){

   10                 return "index";

   11         }

   12         @GetMapping("/admin")

   13         public String admin(){

   14                 return "admin";

   15         }

   16 

   17         @GetMapping("/login")

   18         public String login(){

   19                 return "login";

   20         }

   21 }

  • login.html

    1 <!DOCTYPE html>

    2 <html lang="en" xmlns:th="http://www.thymeleaf.org">

    3 

    4 <head>

    5         <meta charset="UTF-8">

    6         <title>Title</title>

    7 </head>

    8 <body>

    9         <form th:action="@{/login}" method="post">

   10                 用户名:<input type="text" name="username"><br>

   11                 密码:<input type="password" name="password"><br>

   12                 <input type="submit" value="登录">

   13         </form>

   14 </body>

   15 </html>

  • 修改index.html

    1 <!DOCTYPE html>

    2 <html lang="en">

    3 <head>

    4         <meta charset="UTF-8">

    5         <title>Title</title>

    6 </head>

    7 <body>

    8         <h1>Hello World</h1>

    9         <form action="/logout" method="post">

   10                 <input type="submit" value="退出">

   11         </form>

   12 </body>

   13 </html>

  • admin.html

    1 <!DOCTYPE html>

    2 <html lang="en">

    3 <head>

    4         <meta charset="UTF-8">

    5         <title>Title</title>

    6 </head>

    7 <body>

    8         <h1>后台管理系统</h1>

    9         <form action="/logout" method="post">

   10                 <input type="submit" value="退出">

   11         </form>

   12 </body>

   13 </html>

 

posted @ 2020-08-13 22:42  wigginess  阅读(142)  评论(0编辑  收藏  举报