1 项目结构图

2 AnyUserDetailsService

package com.fengyntec.config;

import com.fengyntec.entity.UserEntity;
import com.fengyntec.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service; import java.util.ArrayList;
import java.util.List; @Service
public class AnyUserDetailsService implements UserDetailsService { @Autowired
private UserService userService; @Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
UserEntity userEntity = userService.getByUsername(username);
if (userEntity == null){
System.out.println("用户不存在");
}
List<SimpleGrantedAuthority> simpleGrantedAuthorities = createAuthorities(userEntity.getRoles());
UserDetails userDetails = new User(userEntity.getUsername(),userEntity.getPassword(),simpleGrantedAuthorities);
return userDetails;
} private List<SimpleGrantedAuthority> createAuthorities(String roleStr){
String[] roles = roleStr.split(",");
List<SimpleGrantedAuthority> simpleGrantedAuthorities = new ArrayList<>();
for (String role : roles) {
simpleGrantedAuthorities.add(new SimpleGrantedAuthority(role));
}
return simpleGrantedAuthorities;
}
}

3 WebSecurityConfig

package com.fengyntec.config;

import org.springframework.beans.factory.annotation.Autowired;
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;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; @EnableWebSecurity
@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter { @Autowired
private AnyUserDetailsService anyUserDetailsService; @Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf().disable()
.authorizeRequests()
.antMatchers("/user/**").hasRole("USER")
.antMatchers("/admin/**").hasRole("ADMIN")
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login.html")
.permitAll()
;
} /**
* 添加 UserDetailsService, 实现自定义登录校验
*/
@Override
protected void configure(AuthenticationManagerBuilder builder) throws Exception{
builder.userDetailsService(anyUserDetailsService).passwordEncoder(new BCryptPasswordEncoder());
}
}

4 Constant

package com.fengyntec.constant;

public interface Constant {
public static String ROLE_USER = "ROLE_USER";
}

5 HomeController

package com.fengyntec.controller;

import com.fengyntec.service.UserService;
import com.google.gson.Gson;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.annotation.Secured;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController; import java.util.ArrayList;
import java.util.List; @RestController
@EnableGlobalMethodSecurity(securedEnabled = true)
public class HomeController { @Autowired
private UserService userService; @GetMapping("/hell")
public String hello(SecurityContextHolder holder){
System.out.println(holder.toString());
return new Gson().toJson(holder);
} @GetMapping("admin")
public String admin(){
return "admin";
} @GetMapping("/vip")
@Secured("ROLE_VIP")
public String vip(){
return "仅限于vip用户查看";
} @GetMapping("/openVip")
public boolean uodateVip(){
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
List<GrantedAuthority> updateAuthority = new ArrayList<>(auth.getAuthorities());
updateAuthority.add(new SimpleGrantedAuthority("ROLE_VIP"));
Authentication newAuth = new UsernamePasswordAuthenticationToken(auth.getPrincipal(),auth.getCredentials(),updateAuthority);
SecurityContextHolder.getContext().setAuthentication(newAuth);
return true;
}
}

6 UserEntity

package com.fengyntec.entity;

import lombok.Data;

@Data
public class UserEntity {
private Long id; /**
* 账号
*/
private String username; /**
* 密码
*/
private String password; /**
* 昵称
*/
private String nickname; /**
* 权限
*/
private String roles;
}

7 Mapper

package com.fengyntec.mapper;

import com.fengyntec.entity.UserEntity;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.springframework.stereotype.Component; @org.apache.ibatis.annotations.Mapper
@Component
public interface Mapper { @Insert("insert into user(username, password, nickname, roles) values(#{username}, #{password}, #{nickname}, #{roles})")
int insert(UserEntity userEntity); @Select("select * from user where username = #{username}")
UserEntity selectByUsername(@Param("username") String username);
}

8 UserService

package com.fengyntec.service;

import com.fengyntec.constant.Constant;
import com.fengyntec.entity.UserEntity;
import com.fengyntec.mapper.Mapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Primary; @org.springframework.stereotype.Service
@Primary
public class UserService { @Autowired
private Mapper mapper; public boolean insert(UserEntity userEntity){
String username = userEntity.getUsername();
if (exist(username)){
return false;
}
userEntity.setRoles(Constant.ROLE_USER);
int result = mapper.insert(userEntity);
return result == 1 ;
} private boolean exist(String username){
UserEntity userEntity = mapper.selectByUsername(username);
return userEntity != null;
} public UserEntity getByUsername(String username) {
return mapper.selectByUsername(username);
}
}

spring boot 中使用spring security阶段小结的更多相关文章

  1. Spring Boot中使用 Spring Security 构建权限系统

    Spring Security是一个能够为基于Spring的企业应用系统提供声明式的安全访问控制解决方案的安全框架.它提供了一组可以在Spring应用上下文中配置的Bean,为应用系统提供声明式的安全 ...

  2. Spring Boot中使用Spring Security进行安全控制

    我们在编写Web应用时,经常需要对页面做一些安全控制,比如:对于没有访问权限的用户需要转到登录表单页面.要实现访问控制的方法多种多样,可以通过Aop.拦截器实现,也可以通过框架实现(如:Apache ...

  3. 【swagger】1.swagger提供开发者文档--简单集成到spring boot中【spring mvc】【spring boot】

    swagger提供开发者文档 ======================================================== 作用:想使用swagger的同学,一定是想用它来做前后台 ...

  4. 在Spring Boot中使用Spring Security实现权限控制

    丢代码地址 https://gitee.com/a247292980/spring-security 再丢pom.xml <properties> <project.build.so ...

  5. Spring Boot中集成Spring Security 专题

    check to see if spring security is applied that the appropriate resources are permitted: @Configurat ...

  6. Spring Boot 中使用 Spring Security, OAuth2 跨域问题 (自己挖的坑)

    使用 Spring Boot 开发 API 使用 Spring Security + OAuth2 + JWT 鉴权,已经在 Controller 配置允许跨域: @RestController @C ...

  7. Spring Boot 中应用Spring data mongdb

    摘要 本文主要简单介绍下如何在Spring Boot 项目中使用Spring data mongdb.没有深入探究,仅供入门参考. 文末有代码链接 准备 安装mongodb 需要连接mongodb,所 ...

  8. spring boot中扩展spring mvc 源码分析

    首先,确认你是对spring boot的自动配置相关机制是有了解的,如果不了解请看我spring boot相关的源码分析. 通常的使用方法是继承自org.springframework.boot.au ...

  9. spring-boot-starter-security Spring Boot中集成Spring Security

    spring security是springboot支持的权限控制系统. security.basic.authorize-mode 要使用权限控制模式. security.basic.enabled ...

随机推荐

  1. CCNA - Part7:网络层 - ICMP 应该是你最熟悉的协议了

    ICMP 协议 在之前网络层的介绍中,我们知道 IP 提供一种无连接的.尽力而为的服务.这就意味着无法进行流量控制与差错控制.因此在 IP 数据报的传输过程中,出现各种的错误是在所难免的,为了通知源主 ...

  2. 食用Win系统自带的PowerShell登录服务器

    运行powershell输入ssh root@你的服务器ip -p你的端口 切换rm ~/.ssh/known_hosts cmd 运行 ping 你的ip -t一直ping ctrl+c停止 tra ...

  3. three.js 数学方法之Box3

    从今天开始郭先生就会说一下three.js 的一些数学方法了,像Box3.Plane.Vector3.Matrix3.Matrix4当然还有欧拉角和四元数.今天说一说three.js的Box3方法(B ...

  4. [jvm] -- 垃圾收集器篇

    垃圾收集器 Serial 收集器 单线程收集器,不仅仅意味着它只会使用一条垃圾收集线程去完成垃圾收集工作,更重要的是它在进行垃圾收集工作的时候必须暂停其他所有的工作线程( "Stop The ...

  5. StringBuilder和 String的区别?

    String在进行运算时(如赋值.拼接等)会产生一个新的实例,而 StringBuilder则不会.所以在大 量字符串拼接或频繁对某一字符串进行操作时最好使用 StringBuilder,不要使用 S ...

  6. JS闭包应用场景之函数回调(含函数的调用个人理解)

    首先我们来绑定一个函数给click事件,这个很好理解,就是创建一个匿名函数作为回调绑定给click事件,如下: 但如果我们想声明一个函数作为回调来绑定多个元素呢,例如下面(注意:绑定事件后不用加括号, ...

  7. java enum 枚举类

    图一代码: public enum LogMethodEnum { WEBCSCARDVALID("返回值"), WEBCSVERIFYPASSWORD("返回值&quo ...

  8. Mybatis——@MapperScan原理

    @MapperScan配置在@Configuration注解的类上会导入MapperScannerRegistrar类. 而MapperScannerRegistrar实现了ImportBeanDef ...

  9. Flutter + Android 混合开发

    JIT (Just In Time) 即时编译器, 边执行边编译 程序运行时,JIT 编译器选择将最频繁执行的方法编译成本地代码.运行时才进行本地代码编译而不是在程序运行前进行编译 AOT可以理解为“ ...

  10. windows系统远程修改密码

    1.需求:公司需要短时间.批量修改一些windows系统的管理员密码: 2.准备工作: a.下载软件:链接:https://pan.baidu.com/s/1kV52DqE1_4siPuxS5Mosc ...