随笔 - 134,  文章 - 0,  评论 - 0,  阅读 - 21282

Spring Boot 整合Spring Seccurity

1.创建maven工程

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>org.example</groupId>
    <artifactId>springsecurity</artifactId>
    <version>1.0-SNAPSHOT</version>
    <parent>
        <artifactId>spring-boot-starter-web</artifactId>
        <groupId>org.springframework.boot</groupId>
        <version>2.2.4.RELEASE</version>
    </parent>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</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-security</artifactId>
        </dependency>
    </dependencies>
</project>

权限管理的开发

权限付给角色,角色付给用户

2.Handler

package com.southwind.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;

@Controller
public class SecurtyHandler {
    @GetMapping("/index")
    public String index(){
        return "index";
    }
}

3.HTML

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <p>idnex</p>
    <form method="post" action="/login">
        <input type="submit" value="退出">
    </form>
</body>
</html>

4.配置文件

spring:
  thymeleaf:
    suffix: .html
    prefix: classpath:/templates/

5.启动类

package com;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;

@SpringBootApplication
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class,args);
    }
}

用户名默认user

密码:默认随机

自定义:

spring:
  thymeleaf:
    suffix: .html
    prefix: classpath:/templates/
  security:
    user:
      name: admin
      password: 123456

权限管理

定义两个资源:

  • index.html

    package com.southwind.Config;
    
    import org.springframework.context.annotation.Configuration;
    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.WebSecurityConfigurerAdapter;
    @Configuration
    public class SecurityConfig extends WebSecurityConfigurerAdapter {
        /**
         * 角色和资源
         * @param http
         * @throws Exception
         */
        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http.authorizeRequests()
                    .antMatchers("/admin").hasRole("ADMIN")
                    .antMatchers("/index").access("hasRole('ADMIN') or hasRole('USER')")
                    .anyRequest().authenticated()
                    .and()
                    .formLogin()
                    .loginPage("/login")
                    .permitAll()
                    .and()
                    .logout()
                    .permitAll()
                    .and()
                    .csrf()
                    .disable();
        }
    
        /**
         * 用户和角色
         * @param auth
         * @throws Exception
         */
        @Override
        protected void configure(AuthenticationManagerBuilder auth) throws Exception {
           auth.inMemoryAuthentication().passwordEncoder(new MypasswordEncoder())
                   .withUser("user").password(new MypasswordEncoder()
                   .encode("000")).roles("USER")
                   .and()
                   .withUser("admin").password(new MypasswordEncoder()
                   .encode("123")).roles("ADMIN","uSER");
        }
    }
    
  • admin.html

定义两个角色:

  • ADMIN访问index.html
  • USER访问index.html

1.创建SecurityConfig

2.自定义MypasswordEncoder类

package com.southwind.Config;

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

public class MypasswordEncoder implements PasswordEncoder {

    @Override
    public String encode(CharSequence charSequence) {
        return charSequence.toString();
    }

    @Override
    public boolean matches(CharSequence charSequence, String s) {
        return s.equals((charSequence.toString()));
    }
}
package com.southwind.Config;

import org.springframework.context.annotation.Configuration;
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.WebSecurityConfigurerAdapter;
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    /**
     * 角色和资源
     * @param http
     * @throws Exception
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers("/admin").hasRole("ADMIN")
                .antMatchers("/index").access("hasRole('ADMIN') or hasRole('USER')")
                .anyRequest().authenticated()
                .and()
                .formLogin()
                .loginPage("/login")
                .permitAll()
                .and()
                .logout()
                .permitAll()
                .and()
                .csrf()
                .disable();
    }

    /**
     * 用户和角色
     * @param auth
     * @throws Exception
     */
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
       auth.inMemoryAuthentication().passwordEncoder(new MypasswordEncoder())
               .withUser("user").password(new MypasswordEncoder()
               .encode("000")).roles("USER")
               .and()
               .withUser("admin").password(new MypasswordEncoder()
               .encode("123")).roles("ADMIN","uSER");
    }
}

4.Handler

package com.southwind.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;

@Controller
public class SecurtyHandler {
    @GetMapping("/index")
    public String index(){
        return "index";
    }
    @GetMapping("/admin")
    public String admin(){
        return "adimin";
    }
    @GetMapping("/login")
    public String login(){
        return "login";
    }
}

5.HTML

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <p>后台管理系统</p>
    <form method="post" action="/logout">
        <input type="submit" value="退出">
    </form>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <p>欢迎回来</p>
    <form method="post" action="/logout">
        <input type="submit" value="退出">
    </form>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <p th:if="%{param.error}">
        用户名或密码错误
    </p>
    <form th:action="@{/login}" method="post">
       用户名:<input type="text" name="username"><br>
        密码:<input type="password" name="password"><br>
        <input type="submit" value="登录">
    </form>
</body>
</html>
posted on   Steam残酷  阅读(523)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· .NET Core 中如何实现缓存的预热?
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 如何调用 DeepSeek 的自然语言处理 API 接口并集成到在线客服系统
点击右上角即可分享
微信分享提示