上个博客: 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(三)使用注解实现权限控制的更多相关文章

  1. springboot整合security实现基于url的权限控制

    权限控制基本上是任何一个web项目都要有的,为此spring为我们提供security模块来实现权限控制,网上找了很多资料,但是提供的demo代码都不能完全满足我的需求,因此自己整理了一版. 在上代码 ...

  2. SpringBoot系列——Security + Layui实现一套权限管理后台模板

    前言 Spring Security官网:https://spring.io/projects/spring-security Spring Security是一个功能强大且高度可定制的身份验证和访问 ...

  3. struts2拦截器加自定义注解实现权限控制

    https://blog.csdn.net/paul342/article/details/51436565 今天结合Java的Annotation和Struts2进行注解拦截器权限控制. 功能需求: ...

  4. Spring Security实现统一登录与权限控制

    1  项目介绍 最开始是一个单体应用,所有功能模块都写在一个项目里,后来觉得项目越来越大,于是决定把一些功能拆分出去,形成一个一个独立的微服务,于是就有个问题了,登录.退出.权限控制这些东西怎么办呢? ...

  5. SpringBoot Spring Security 核心组件 认证流程 用户权限信息获取详细讲解

    前言 Spring Security 是一个安全框架, 可以简单地认为 Spring Security 是放在用户和 Spring 应用之间的一个安全屏障, 每一个 web 请求都先要经过 Sprin ...

  6. springboot通过AOP和自定义注解实现权限校验

    自定义注解 PermissionCheck: package com.mgdd.sys.annotation; import java.lang.annotation.*; /** * @author ...

  7. Spring Boot+Spring Security+JWT 实现 RESTful Api 权限控制

    摘要:用spring-boot开发RESTful API非常的方便,在生产环境中,对发布的API增加授权保护是非常必要的.现在我们来看如何利用JWT技术为API增加授权保护,保证只有获得授权的用户才能 ...

  8. spring boot系列03--spring security (基于数据库)登录和权限控制(下)

    (接上篇) 后台 先说一下AuthConfig.java Spring Security的主要配置文件之一 AuthConfig 1 @Configuration 2 @EnableWebSecuri ...

  9. spring boot系列--spring security (基于数据库)登录和权限控制

    先说一下AuthConfig.java Spring Security的主要配置文件之一 AuthConfig 1 @Configuration 2 @EnableWebSecurity 3 publ ...

随机推荐

  1. (转)忘记wamp-mysql数据库root用户密码重置方法

    转自:http://www.jb51.net/article/28883.htm 1.打开任务管理器,结束进程  mysqld-nt.exe . 2.运行命令窗口 1)进行php服务管理器安装目录中的 ...

  2. 20155326 2016-2017-2《Java程序设计》课程总结

    20155326 2016-2017-2<Java程序设计>课程总结 (按顺序)每周作业链接汇总 20155326刘美岑的第一次作业:第一次写博客,写下了对java的期待 20155326 ...

  3. Codeforces820A Mister B and Book Reading 2017-06-28 09:38 67人阅读 评论(0) 收藏

    A. Mister B and Book Reading time limit per test 2 seconds memory limit per test 256 megabytes input ...

  4. 七种bond模式说明

    第一种模式:mod=0 ,即:(balance-rr) Round-robin policy(平衡抡循环策略) 特点:传输数据包顺序是依次传输(即:第1个包走eth0,下一个包就走eth1….一直循环 ...

  5. 程序员、技术领导、管理者各有烦恼,你占了几条?ZZ

    Q1: 作为学生,你学习 SE的烦恼有哪些? http://blog.jobbole.com/101840/

  6. linux上安装python2.7.11

    好久不玩儿linux了,本来就不熟,现在几乎白痴.步骤如下: 从python官网上下载python的源代码 tar zvxf后得到一个文件夹: 进入Python-2.7.11,按照https://do ...

  7. Azure DevOps Server (TFS)中代码文件换行问题解决方案(Git)

    之前写过一篇博客"探索TFS Git 库文件换行(CRLF)的处理方式",主要是针对TFVC代码库的. 下面这篇文章说明如何在TFS的Git库中处理代码换行的问题. 概述 在Azu ...

  8. 聊聊如何设计千万级吞吐量的.Net Core网络通信!

    聊聊如何设计千万级吞吐量的.Net Core网络通信! 作者:大石头 时间:2018-10-26 晚上 20:00 地点:QQ群-1600800 内容:网络通信, 网络库使用方式 网络库设计理念,高性 ...

  9. ovs flow 命令集

    流表可以有多个执行动作,是从左向右以此执行,常用动作如下: output:port: 输出数据包到指定的端口.port 是指端口的 OpenFlow 端口编号 group:group_id 输出数据包 ...

  10. 1月第2周业务风控关注|“扫黄打非”部门查处互动作业、纳米盒等20多个学习类App

    易盾业务风控周报每周呈报值得关注的安全技术和事件,包括但不限于内容安全.移动安全.业务安全和网络安全,帮助企业提高警惕,规避这些似小实大.影响业务健康发展的安全风险. 1.全国"扫黄打非&q ...