Spring Security的使用

为了让小伙伴更快了解Spring Security的使用,现在以代码格式展现: 

工程目录:


pom.xml

<?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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.2.5.RELEASE</version>
		<relativePath/> <!-- lookup parent from repository -->
	</parent>
	<groupId>com.newer</groupId>
	<artifactId>security</artifactId>
	<version>0.1</version>
	<name>security</name>
	<description>Demo project for Spring Boot</description>

	<properties>
		<java.version>11</java.version>
	</properties>

	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-security</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-devtools</artifactId>
			<scope>runtime</scope>
			<optional>true</optional>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
			<exclusions>
				<exclusion>
					<groupId>org.junit.vintage</groupId>
					<artifactId>junit-vintage-engine</artifactId>
				</exclusion>
			</exclusions>
		</dependency>
		<dependency>
			<groupId>org.springframework.security</groupId>
			<artifactId>spring-security-test</artifactId>
			<scope>test</scope>
		</dependency>
	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>

</project>

application.yml(右击项目---点击Configure----点击Convert application.ym:转换)

spring:
  security:
    user:
      name: test
      password: test
      roles:
      - stu
      - admin
#  datasource:
#    url: 
#    username: 
#    password: 
#    driver-class-name: 

  http:
    log-request-details: true

logging:
  level:
    web: debug

SecurityApplication.java

package com.newer.security;

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

@SpringBootApplication
public class SecurityApplication {

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

}

SecurityConfig.java

package com.newer.security.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.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

//Spring早期版本中是写在XML中的
//WebSecurityConfigurerAdapter:web安全配置适配器(抽象类)
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter{

	/**
	 * 设置URL的授权
	 */
	@Override
	protected void configure(HttpSecurity http) throws Exception {
		
//		super.configure(http);
		
		http.authorizeRequests()
			.antMatchers("/","/home").permitAll()
			.antMatchers("/admin").hasRole("admin")
			.antMatchers("/stu","/stu/*").hasRole("stu")
			.anyRequest().authenticated()
			.and()
			.formLogin().defaultSuccessUrl("/welcome").failureUrl("/error")
//			.formLogin().loginPage("/login").defaultSuccessUrl("/welcome")  //使用自定义的界面
			.and()
			.httpBasic();
		
//		默认值
//		http
//			.authorizeRequests()   //请求的认证方式
//				.anyRequest().authenticated()  //任意请求都是认证用户可见
//				.and()  
//			.formLogin().and() 	//设置基于表单的登录(内置的)
//			.httpBasic();
		
	}
	
	
	/**
	 * 认证管理
	 */
	@Override
	protected void configure(AuthenticationManagerBuilder auth) throws Exception {
		
		super.configure(auth);
		
//		配置文件存储(默认)
		
//		内存中存储用户认证信息
//		auth.inMemoryAuthentication()
//			.withUser("").password("").roles("")
//			.and()
//			.withUser("").password("").roles("")
//			.and()
//			.withUser("").password("").roles("");
			
//		JWT
//		数据库存储
//		auth.jdbcAuthentication()
//			.authoritiesByUsernameQuery("")
//			.passwordEncoder(null);
//			
		
		
	}
	
	
}

OtherController.java

package com.newer.security;

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

@Controller
public class OtherController {

	@GetMapping("/login")
	public String login() {
		
//	login.html中提交数据字段名必须是以下格式	
		
		return "login.html";
	}
}

HomeController.java

package com.newer.security;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class HomeController {

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

	  @GetMapping("/home")
	  public String home() {
	    return "home";
	  }

	  @GetMapping("/admin")
	  public String admin() {
	    return "admin";
	  }

	  @GetMapping("/stu")
	  public String stus() {
	    return "stu list";
	  }

	  @GetMapping("/stu/{id}")
	  public String stu(@PathVariable String id) {
	    return "stu: " + id;
	  }
	  
	  @GetMapping("/error")
	  public String error() {
	    return "error";
	  }
	  
	  @GetMapping("/welcome")
	  public String welcome() {
	    return "welcome";
	  }
	  
}

运行程序,浏览器打开

/,/home可以直接访问,但是/admin,/stu必须登录后才能访问,图为/admin


再次点击 /admin

 


 以上就是Spring Security的使用,有问题的小伙伴,欢迎私信或者留言!!!

原创文章 145 获赞 482 访问量 4万+

猜你喜欢

转载自blog.csdn.net/weixin_44364444/article/details/105842277