Spring Boot 使用Spring security
1.Spring Boot 内置属性参数
security.basic.authorize-mode=role # 应用授权模式,ROLE=成员必须是安全的角色,AUTHENTICATED=经过身份验证的用户,NONE=没有设置安全授权
security.basic.enabled=true # 启用基本身份认证
security.basic.path=/** # 拦截策略,以逗号分隔
security.basic.realm=Spring # HTTP基本realm
security.enable-csrf=false # 启用csrf支持
security.filter-order=0 # 过滤器执行顺序
security.filter-dispatcher-types=ASYNC, FORWARD, INCLUDE, REQUEST # security 过滤器链dispatcher类型
security.headers.cache=true # 启用缓存控制 HTTP headers.
security.headers.content-type=true # 启用 "X-Content-Type-Options" header.
security.headers.frame=true # 启用 "X-Frame-Options" header.
security.headers.hsts= # HTTP Strict Transport Security (HSTS) mode (none, domain, all).
security.headers.xss=true # 启用跨域脚本 (XSS) 保护.
security.ignored= # 安全策略,以逗号分隔
security.require-ssl=false # 启用所有请求SSL
security.sessions=stateless # Session 创建策略(always, never, if_required, stateless).
security.user.name=user # 默认用户名
security.user.password= # 默认用户名密码
security.user.role=USER # 默认用户角色
# SECURITY OAUTH2 CLIENT (OAuth2ClientProperties 类中)
security.oauth2.client.client-id= # OAuth2 client id.
security.oauth2.client.client-secret= # OAuth2 client secret. A random secret is generated by default
# SECURITY OAUTH2 RESOURCES (ResourceServerProperties 类中)
security.oauth2.resource.id= # Identifier of the resource.
security.oauth2.resource.jwt.key-uri= # The URI of the JWT token. Can be set if the value is not available and the key is public.
security.oauth2.resource.jwt.key-value= # The verification key of the JWT token. Can either be a symmetric secret or PEM-encoded RSA public key.
security.oauth2.resource.prefer-token-info=true # Use the token info, can be set to false to use the user info.
security.oauth2.resource.service-id=resource #
security.oauth2.resource.token-info-uri= # URI of the token decoding endpoint.
security.oauth2.resource.token-type= # The token type to send when using the userInfoUri.
security.oauth2.resource.user-info-uri= # URI of the user endpoint.
# SECURITY OAUTH2 SSO (OAuth2SsoProperties 类中)
security.oauth2.sso.filter-order= # Filter order to apply if not providing an explicit WebSecurityConfigurerAdapter
security.oauth2.sso.login-path=/login # Path to the login page, i.e. the one that triggers the redirect to the OAuth2 Authorization Server
2.security Starter Poms
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
3.security hello world
3.1创建工程
<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>com.chengli</groupId>
<artifactId>springboot-security</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>springboot-security</name>
<url>http://maven.apache.org</url>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.4.3.RELEASE</version>
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<optional>true</optional>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
3.2创建入口启动类
package com.chengli.springboot;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@SpringBootApplication
@EnableWebSecurity //启用web安全
public class MainConfig {
public static void main(String[] args) {
SpringApplication.run(MainConfig.class, args);
}
@RequestMapping("/security")
public String security() {
return "hello world security";
}
}
3.3创建application.properties
security.user.name=chengli
security.user.password=123456
3.4启动

4.自定义security
4.1新建security配置类:SecurityConfig
package com.chengli.springboot.security;
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;
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
/**定义认证用户信息获取来源,密码校验规则等*/
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
//inMemoryAuthentication 从内存中获取
auth.inMemoryAuthentication().withUser("chengli").password("123456").roles("USER");
//jdbcAuthentication从数据库中获取,但是默认是以security提供的表结构
//usersByUsernameQuery 指定查询用户SQL
//authoritiesByUsernameQuery 指定查询权限SQL
//auth.jdbcAuthentication().dataSource(dataSource).usersByUsernameQuery(query).authoritiesByUsernameQuery(query);
//注入userDetailsService,需要实现userDetailsService接口
//auth.userDetailsService(userDetailsService);
}
/**定义安全策略*/
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()//配置安全策略
.antMatchers("/","/hello").permitAll()//定义/请求不需要验证
.anyRequest().authenticated()//其余的所有请求都需要验证
.and()
.logout()
.permitAll()//定义logout不需要验证
.and()
.formLogin();//使用form表单登录
}
}
4.2在入口启动类MainConfig加入以下方法
@RequestMapping("/hello")
public String hello() {
return "不验证哦";
}
4.4启动
4.5开启方法权限校验
@PreAuthorize("hasRole('ROLE_ADMIN')")
@RequestMapping("/authorize")
public String authorize() {
return "有权限访问";
}
在增加一个用户admin,修改以下代码,如下:
修改前:
auth.inMemoryAuthentication().withUser("chengli").password("123456").roles("USER")
修改后:
auth.inMemoryAuthentication().withUser("chengli").password("123456").roles("USER")
.and().withUser("admin").password("123456").roles("ADMIN");
这里我们在启动使用chengli登录后访问/authorize会返回403错误,使用admin登录访问页面输出有权限访问。
//禁用csrf
http.csrf().disable();
1690



被折叠的 条评论
为什么被折叠?



