前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >基于spring security实现接口权限控制

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

作者头像
用户5166330
发布2019-12-24 11:24:05
2.7K0
发布2019-12-24 11:24:05
举报
文章被收录于专栏:帅哥哥写代码帅哥哥写代码

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

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

代码语言:javascript
复制
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)
代码语言:javascript
复制
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);
        }
    }
}
代码语言:javascript
复制
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')")
代码语言:javascript
复制
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')")
代码语言:javascript
复制
    @GetMapping(value = "/user2")
    public UserView getUserByName2(@RequestParam("userName") String userName,Authentication au) {
        System.out.println("11111111111");
        System.out.println(au);
        return userService.getUserByUserName(userName);
    }
}
代码语言:javascript
复制
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')")
代码语言:javascript
复制
    @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配置类

代码语言:javascript
复制
   @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')")
代码语言:javascript
复制
                    .anyRequest().authenticated()
                    .and().formLogin().loginProcessingUrl("/api/login")
                    .successHandler(successHandler)
                    .failureHandler(failHandler)
                    .and().exceptionHandling().authenticationEntryPoint(entryPoint);
        }
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 基于spring security实现接口权限控制
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档