Spring-Security是SpringBoot推荐的安全框架,配置简单,功能强大。
依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
Controller
@RestController
@EnableWebSecurity
public class Controller {
@GetMapping()
public String Main(){
return "Hello Spring-Security!!!";
}
}
配置:用户名密码
spring.security.user.name=taoyuan
spring.security.user.password=123456
默认用户名user,密码随机分配会打印在日志中
进入设定的url中,并不是直接显示Hello Spring-Security!!!
,而是一个登录页,输入设定的用户名密码才会进入到真正的首页。
然而在实际开发中,涉及到安全方面的问题,一般不太会用默认,所以要自定义
创建配置类
package com.jiataoyuan.demo.springsecurity.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;
/**
* @author TaoYuan
* @version V1.0.0
* @date 2018/4/21 0021
* @description WebSecurityConfigurerAdapter是security提供用于更改默认配置
* 实现configure方法可完成配置
*/
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
/**定义认证用户信息获取来源,密码校验规则等*/
// @Override
// protected void configure(AuthenticationManagerBuilder auth) throws Exception {
// //inMemoryAuthentication 从内存中获取
//// auth.inMemoryAuthentication().withUser("test").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 {
String[] patterns = {"/", "/no-check"};
http.authorizeRequests()//配置安全策略
.antMatchers(patterns).permitAll()//定义不需要验证接口,String[]
.anyRequest().authenticated()//其余的所有请求都需要验证
.and()
.logout()
.permitAll()//定义logout不需要验证
.and()
.formLogin();//使用form表单登录
}
}
controller
package com.jiataoyuan.demo.springsecurity.controller;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* @author TaoYuan
* @version V1.0.0
* @date 2018/4/21 0021
* @description description
*/
@RestController
@EnableWebSecurity
public class Controller {
@GetMapping()
public String Main(){
return "Hello Spring-Security!!!";
}
@RequestMapping("/check")
public String Check() {
return "验证通过";
}
@RequestMapping("/no-check")
public String noCheck() {
return "不验证";
}
}
运行试试吧
网友评论