专栏首页帅哥哥写代码基于spring security实现接口权限控制

基于spring security实现接口权限控制

基于spring security实现接口权限控制

一、基于注解 (1)在security配置文件上配置@EnableGlobalMethodSecurity(prePostEnabled = true)注解 (2)在具体类上加@PreAuthorize("hasAuthority('admin_s1')")或者方法上加上@PreAuthorize("hasAuthority('admin_s1')") 代码示例如下

package com.ysh.springboot.test.config;

import com.sayo.authlogin.auth.JwtAuthenticationFilter;
import com.sayo.authlogin.service.DatabaseUserDetailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
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.config.http.SessionCreationPolicy;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;


@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig {

    @Configuration
    public static class MySecurityConfig extends WebSecurityConfigurerAdapter {

        @Autowired
        @Qualifier("databaseUserDetailService")
        private DatabaseUserDetailService userDetailsService;

        @Autowired
        @Qualifier("authenticationSuccessHandler")
        private AuthenticationSuccessHandler successHandler;

        @Autowired
        @Qualifier("authenticationFailHandler")
        private AuthenticationFailHandler failHandler;

        @Autowired
        @Qualifier("authenticationEntryPointImpl")
        private AuthenticationEntryPoint entryPoint;

        @Bean
        public JwtAuthenticationFilter getJwtAuthenticationFilter(){
            return new JwtAuthenticationFilter();
        }

        @Override
        public void configure(HttpSecurity http) throws Exception {
           // http.addFilterBefore(getJwtAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class)
            http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                    .and().csrf().disable()
                    .authorizeRequests()
                    .antMatchers("/v2/api-docs/**").permitAll()
                    .anyRequest().authenticated()
                    .and().formLogin().loginProcessingUrl("/api/login")
                    .successHandler(successHandler)
                    .failureHandler(failHandler)
                    .and().exceptionHandling().authenticationEntryPoint(entryPoint);
        }

        @Override
        protected void configure(AuthenticationManagerBuilder auth) throws Exception {
            auth.userDetailsService(userDetailsService);
        }
    }
}
package com.ysh.springboot.test.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.ysh.springboot.test.service.UserService;
import com.ysh.springboot.test.valueobject.UserView;


@RestController
@RequestMapping("/api")
//@PreAuthorize("hasAuthority('admin_s1')")
public class UserController {

    @Autowired
    private UserService userService;

    @GetMapping(value = "/user")
    public UserView getUserByName(@RequestParam("userName") String userName,Authentication au) {
        System.out.println("11111111111");
        System.out.println(au);
        return userService.getUserByUserName(userName);
    }
@PreAuthorize("hasAuthority('admin_s1')")
    @GetMapping(value = "/user2")
    public UserView getUserByName2(@RequestParam("userName") String userName,Authentication au) {
        System.out.println("11111111111");
        System.out.println(au);
        return userService.getUserByUserName(userName);
    }
}
package com.ysh.springboot.test.service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
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.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.ysh.springboot.test.domain.User;
import com.ysh.springboot.test.repository.UserRepository;
import com.ysh.springboot.test.valueobject.UserView;

@Service
public class UserService {

    @Autowired
    private UserRepository userRepository;
@PreAuthorize("hasAuthority('admin_s11')")
    @Transactional
    public UserView getUserByUserName(String userName){

        UserView userView = new UserView();
        User user = userRepository.findByUserName(userName);
        userView.setUserName(user.getUserName());
        userView.setUserDesc(user.getUserDescription());
        List<String> roleCodes = new ArrayList<>();
        user.getRoles().stream().forEach(role -> roleCodes.add(role.getRoleCode()));
        userView.setRoleCodes(roleCodes);
        return userView;
    }
}

二、基于SecurityConfig配置类

   @Override
        public void configure(HttpSecurity http) throws Exception {
            http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                    .and().csrf().disable()
                    .authorizeRequests()
                    .antMatchers("/v2/api-docs/**").permitAll()
.antMatchers("/api/*").access("hasAuthority('admin_s3')")
                    .anyRequest().authenticated()
                    .and().formLogin().loginProcessingUrl("/api/login")
                    .successHandler(successHandler)
                    .failureHandler(failHandler)
                    .and().exceptionHandling().authenticationEntryPoint(entryPoint);
        }

本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。

我来说两句

0 条评论
登录 后参与评论

相关文章

  • JPA关联关系表中加其他字段

    JPA是Java Persistence API的简称,中文名Java持久层API,是JDK 5.0注解或XML描述对象-关系表的映射关系,并将运行期的实体[对...

    用户5166330
  • 利用springcloud搭建微服务集成中心

    整体目录结构 这里整个功能是一个maven项目,注册中心与功能服务都是maven项目里面的模块。

    用户5166330
  • 自定义工作流设计

    工作偶尔会遇到需要审批相关的系统,对于流程步骤相对固定的,一般会采取某些第三方的工作流来做对应的系统。目前唯一用过的就是activiti工作流。对它进行了简单的...

    用户5166330
  • SpringCloud系列之使用Feign进行服务调用

    在上一章的学习中,我们知道了微服务的基本概念,知道怎么基于Ribbon+restTemplate的方式实现服务调用,接着上篇博客,我们学习怎么基于Feign实现...

    SmileNicky
  • springboot scheduled并发配置

    本文介绍如何使用springboot的sheduled实现任务的定时调度,并将调度的任务实现为并发的方式。 1、定时调度配置scheduled 1)注册定时任务...

    用户1225216
  • SpringMvc源码之解析参数HandlerMethodArgumentResolver

    HandlerMethodArgumentResolver是什么?它是springmvc提供的入参解析器,像平常应用的注解@RequestParam @Path...

    奕仁
  • Springboot项目的接口防刷

    JAVA葵花宝典
  • Springboot项目的接口防刷(实例)

    Java团长
  • Springboot项目的接口防刷(实例)

    链接:blog.csdn.net/weixin_42533856/article/details/82593123

    良月柒
  • Spring Boot 项目的 API 接口防刷

    来源:blog.csdn.net/weixin_42533856/article/details/82593123

    芋道源码

扫码关注云+社区

领取腾讯云代金券