springboot-30-security(三)使用注解实现权限控制
上个博客: http://www.cnblogs.com/wenbronk/p/7381252.html中, 实现了经典5表对用户进行权限的控制, 但太过于繁琐了, 官方推荐的方式是将用户和角色存储数据库, 权限直接在要访问的接口上进行控制
(我感觉更麻烦...每个接口都需要指定)
本篇基于第一个, security: http://www.cnblogs.com/wenbronk/p/7379865.html
一, 数据库: (更多可见 security(1) )
1, 数据表:
SET FOREIGN_KEY_CHECKS=; -- ----------------------------
-- Table structure for `sys_user`
-- ----------------------------
DROP TABLE IF EXISTS `sys_user`;
CREATE TABLE `sys_user` (
`id` INT () NOT NULL AUTO_INCREMENT COMMENT '主键id',
`username` varchar() DEFAULT NULL COMMENT '用户名',
`password` varchar() DEFAULT NULL COMMENT '密码',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT= DEFAULT CHARSET=utf8; -- ----------------------------
-- Table structure for `sys_role`
-- ----------------------------
DROP TABLE IF EXISTS `sys_role`;
CREATE TABLE `sys_role` (
`id` INT () NOT NULL AUTO_INCREMENT COMMENT '主键id',
`name` varchar() DEFAULT NULL COMMENT '用户名',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT= DEFAULT CHARSET=utf8; -- ----------------------------
-- Table structure for `sys_role_user`
-- ----------------------------
DROP TABLE IF EXISTS `sys_role_user`;
CREATE TABLE `sys_role_user` (
`id` int() NOT NULL AUTO_INCREMENT COMMENT '主键id',
`sys_user_id` INT() NOT NULL COMMENT 'user_id',
`sys_role_id` INT() NOT NULL COMMENT 'role_id',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT= DEFAULT CHARSET=utf8; ALTER TABLE sys_role_user ADD CONSTRAINT sys_FK1 FOREIGN KEY(sys_user_id) REFERENCES sys_user(id);
ALTER TABLE sys_role_user ADD CONSTRAINT role_FK2 FOREIGN KEY(sys_role_id) REFERENCES sys_role(id);
2, 插入数据
insert into SYS_USER (id,username, password) values (,'vini', '$2a$10$n7sdY5rR1X3XOfZR6o2R.OdW0vvz3uidz0UEzVKV0CEyu0hGwIch.');
insert into SYS_USER (id,username, password) values (,'bronk', '$2a$10$n7sdY5rR1X3XOfZR6o2R.OdW0vvz3uidz0UEzVKV0CEyu0hGwIch.'); insert into SYS_ROLE(id,name) values(,'ROLE_ADMIN');
insert into SYS_ROLE(id,name) values(,'ROLE_USER'); insert into SYS_ROLE_USER(SYS_USER_ID,sys_role_id) values(,);
insert into SYS_ROLE_USER(SYS_USER_ID,sys_role_id) values(,);
这儿使用了 Bcrpy强hash加密, 我设置的密码为 123,
更多可见: http://blog.csdn.net/u012373815/article/details/60465776
3, 映射实体
SysUser.groovy
package com.wenbronk.security.entity import com.fasterxml.jackson.annotation.JsonIgnore
import org.springframework.security.core.GrantedAuthority
import org.springframework.security.core.userdetails.UserDetails /**
* Created by wenbronk on 2017/8/14.
*/
class SysUser implements UserDetails {
int id
String username
@JsonIgnore
String password
String rawPass
@JsonIgnore
List<SysRole> roles
List<? extends GrantedAuthority> authorities @Override
@JsonIgnore
Collection<? extends GrantedAuthority> getAuthorities() {
return authorities
} @Override
@JsonIgnore
boolean isAccountNonExpired() {
return true
} @Override
@JsonIgnore
boolean isAccountNonLocked() {
return true
} @Override
@JsonIgnore
boolean isCredentialsNonExpired() {
return true
} @Override
@JsonIgnore
boolean isEnabled() {
return true
} @Override
public String toString() {
return "SysUser{" +
"id=" + id +
", username='" + username + '\'' +
", password='" + password + '\'' +
", rawPass='" + rawPass + '\'' +
", roles=" + roles +
", authorities=" + authorities +
'}';
}
}
SysRole.groovy
package com.wenbronk.security.entity
/**
* Created by wenbronk on 2017/8/14.
*/
class SysRole {
int id
String name @Override
public String toString() {
return "SysRole{" +
"id=" + id +
", name=" + name +
'}';
}
}
4, mapper
SysUserMapper.groovy
package com.wenbronk.security.mapper import com.wenbronk.security.entity.SysUser /**
* Created by wenbronk on 2017/8/14.
*/
interface SysUserMapper {
SysUser findByUserName(String username)
}
SysUserMapper.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.wenbronk.security.mapper.SysUserMapper"> <resultMap id="sys_user_map" type="SysUser">
<id property="id" column="id" />
<result property="username" column="username" />
<result property="password" column="password" />
<collection property="roles" ofType="SysRole">
<result column="name" property="name" />
</collection> </resultMap> <select id="findByUserName" parameterType="string" resultMap="sys_user_map">
select u.id, u.username, u.password, r.name
from sys_user u
LEFT JOIN sys_role_user s on u.id = s.sys_user_id
LEFT JOIN sys_role r on r.id = s.sys_role_id
WHERE username = #{username}
</select>
</mapper>
二, security
1, WebSecurityConfig.groovy
package com.wenbronk.security.security.config import com.wenbronk.security.security.interceptor.MyFilterSecurityInterceptor
import com.wenbronk.security.security.service.CustomUserService
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.context.annotation.Configuration
import org.springframework.http.HttpMethod
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity
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 import javax.inject.Inject
/**
* Created by wenbronk on 2017/8/15.
*/
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(securedEnabled = true) // 控制权限注解
class WebSecurityConfig extends WebSecurityConfigurerAdapter { @Inject
CustomUserService customUserService;
@Autowired
MyFilterSecurityInterceptor myFilterSecurityInterceptor /**
* 设置加密方式为 BCrypt强hash
*/
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(customUserService).passwordEncoder(new BCryptPasswordEncoder());
} @Override
protected void configure(HttpSecurity http) throws Exception {
// 关闭 csrf()
http.csrf().disable()
.authorizeRequests()
.antMatchers("/users**").authenticated()
.antMatchers(HttpMethod.POST).authenticated()
.antMatchers(HttpMethod.PUT).authenticated()
.antMatchers(HttpMethod.DELETE).authenticated()
.antMatchers("/**")
.permitAll()
.and()
.sessionManagement()
// 使用basic认证登陆
.and().httpBasic()
}
}
这儿需要关闭 csrf 和使用 basic 认证, 相信可见:
http://blog.csdn.net/u012373815/article/details/55047285
http://blog.csdn.net/u012373815/article/details/56832167
CustomerUserService.groovy
package com.wenbronk.security.security.service import com.wenbronk.security.entity.SysUser
import com.wenbronk.security.mapper.SysUserMapper
import org.springframework.security.core.GrantedAuthority
import org.springframework.security.core.authority.SimpleGrantedAuthority
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 javax.inject.Inject
/**
* Created by wenbronk on 2017/8/15.
*/
@Service
class CustomUserService implements UserDetailsService { @Inject
SysUserMapper sysUserMapper
// @Inject
// SysPermissionMapper sysPermissionMapper @Override
UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
def sysUser = sysUserMapper.findByUserName(s) as SysUser
assert sysUser != null List<GrantedAuthority> authorities = new ArrayList<>()
sysUser.getRoles().each { role ->
// 将用户的权限添加到 authrities中就可以了
authorities.add(new SimpleGrantedAuthority(role.getName()))
}
sysUser.setAuthorities(authorities)
return sysUser }
}
三, 接口控制:
登陆使用的
@RequestMapping(value = "/login")
public Object login(@AuthenticationPrincipal SysUser loginUser, @RequestParam(name = "logout", required = false) String logout) {
if (logout != null) {
return null
}
if (loginUser != null) {
return loginUser
}
return null
}
权限接口控制:
package com.wenbronk.security.controller import com.wenbronk.security.entity.SysUser
import org.springframework.security.access.annotation.Secured
import org.springframework.web.bind.annotation.RequestBody
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RequestMethod
import org.springframework.web.bind.annotation.RestController
/**
* Created by wenbronk on 2017/8/17.
*/
@RestController
@RequestMapping("/users")
class HomeController { /**
* 所有可访问
*/
@RequestMapping(method = RequestMethod.GET)
String getusers() {
'getUsers'
} @Secured(value = ['ROLE_ADMIN', 'ROLE_USER'])
@RequestMapping(method = RequestMethod.POST)
String save(@RequestBody SysUser user) {
user.toString()
} /**
* 只有admin可访问
*/
@Secured(value = ['ROLE_ADMIN'])
@RequestMapping(method = RequestMethod.PUT)
String update() {
'updateUser'
} @Secured(value = ['ROLE_ADMIN'])
@RequestMapping(method = RequestMethod.DELETE)
String delete() {
'deleteUser'
} }
四, 访问:
1, get访问

2, post访问, 请求体为:
{
"id": ,
"username": "vini",
"password": "",
"rawPass": ""
}

3, put请求, 此处使用的用户没有权限

4, delete请求, 换有权限的用户

这样, 就可以实现具体方法的访问权限控制, 包括rest请求
ps: basic64登陆, 需要密码, 可以使用工具生成, 也可以抓包
原博客地址:
http://blog.csdn.net/u012373815/article/details/59749385
springboot-30-security(三)使用注解实现权限控制的更多相关文章
- springboot整合security实现基于url的权限控制
权限控制基本上是任何一个web项目都要有的,为此spring为我们提供security模块来实现权限控制,网上找了很多资料,但是提供的demo代码都不能完全满足我的需求,因此自己整理了一版. 在上代码 ...
- SpringBoot系列——Security + Layui实现一套权限管理后台模板
前言 Spring Security官网:https://spring.io/projects/spring-security Spring Security是一个功能强大且高度可定制的身份验证和访问 ...
- struts2拦截器加自定义注解实现权限控制
https://blog.csdn.net/paul342/article/details/51436565 今天结合Java的Annotation和Struts2进行注解拦截器权限控制. 功能需求: ...
- Spring Security实现统一登录与权限控制
1 项目介绍 最开始是一个单体应用,所有功能模块都写在一个项目里,后来觉得项目越来越大,于是决定把一些功能拆分出去,形成一个一个独立的微服务,于是就有个问题了,登录.退出.权限控制这些东西怎么办呢? ...
- SpringBoot Spring Security 核心组件 认证流程 用户权限信息获取详细讲解
前言 Spring Security 是一个安全框架, 可以简单地认为 Spring Security 是放在用户和 Spring 应用之间的一个安全屏障, 每一个 web 请求都先要经过 Sprin ...
- springboot通过AOP和自定义注解实现权限校验
自定义注解 PermissionCheck: package com.mgdd.sys.annotation; import java.lang.annotation.*; /** * @author ...
- Spring Boot+Spring Security+JWT 实现 RESTful Api 权限控制
摘要:用spring-boot开发RESTful API非常的方便,在生产环境中,对发布的API增加授权保护是非常必要的.现在我们来看如何利用JWT技术为API增加授权保护,保证只有获得授权的用户才能 ...
- spring boot系列03--spring security (基于数据库)登录和权限控制(下)
(接上篇) 后台 先说一下AuthConfig.java Spring Security的主要配置文件之一 AuthConfig 1 @Configuration 2 @EnableWebSecuri ...
- spring boot系列--spring security (基于数据库)登录和权限控制
先说一下AuthConfig.java Spring Security的主要配置文件之一 AuthConfig 1 @Configuration 2 @EnableWebSecurity 3 publ ...
随机推荐
- C++函数的传值调用&指针调用&引用调用
目录 传值调用 指针调用 引用调用 传值调用 该方法把参数的实际值复制给函数的形式参数.在这种情况下,修改函数内的形式参数对实际参数没有影响. #include<iostream> usi ...
- Matlab作图
修改线宽 plot(x,y,'LineWidth',1.5) 在xlabel,ylabel,title中使用latex语言 xlabel('$x$','interpreter','latex') yl ...
- (最长公共子序列 暴力) Common Subsequence (poj 1458)
http://poj.org/problem?id=1458 Description A subsequence of a given sequence is the given sequence w ...
- java poi 合并单元格
java poi 合并单元格 2017年03月29日 16:39:01 翠烟你懊恼 阅读数:26561 版权声明:本文为博主原创文章,未经博主允许不得转载. https://blog.csdn.n ...
- hdu 5074 相邻数和最大dp
http://acm.hdu.edu.cn/showproblem.php?pid=5074 给定一个序列 有些位数未知,给你所有两个数连续所得到的能量,问你怎么安排数字使得总能量最大 二维dp,dp ...
- Java中sleep()与wait()区别(涉及类锁相关概念)
在区别之前,我们首先先了解一下关于对象锁,类锁的相关概念(当时查阅的详细地址:http://www.importnew.com/20444.html,该作者对类锁和对象锁进行了详细的举例分析) 对象锁 ...
- 在 Centos7 的KVM上启用嵌套虚拟化
1.嵌套虚拟化意味着在虚拟机内配置虚拟化环境.换句话说,我们可以说嵌套虚拟化是虚拟机管理程序hypervisor的一个特性,它允许我们通过虚拟化管理程序(宿主机)的硬件加速在虚拟服务器内安装和运行虚拟 ...
- 【WEB前端】CSS书写规范
古语有云:不以规矩,不成方圆.不管是国还是家还是...都得有规矩加以约束.同样,在我们程序猿的代码中也有一定的规矩——W3C标准,但是我今天不会讲那么高深的道理,我只想说说,我近些日子在开发中所总结出 ...
- C#通过字符串名称来调用对应字符串名称的方法
前段时间在一个项目中,在一个地方要将函数所在类中的方法都调用一遍,但是否调用要通过配置文件中的内容决定.所以为了减少代码量,在网上查了相关信息,终于成功的将其应用到了项目中,我在这里将我做的一个简单例 ...
- WPF放大镜效果
在做WPF项目中,不止两个项目需要有放大镜功能. 第一个项目是一个手术室的远程示教系统,主要是为了方便专家演示病症时,可以放大图片上的某些部位. 第二个项目是一个工厂的MES项目,其中有个功能是质量预 ...