Spring Security中的用户授权

基于权限访问控制

hasAuthority

hasAuthority方法:如果当前主体具有指定的权限,则返回true,否则返回false,适用于单个权限。

示例,基于Spring Security中的自定义用户登录页面

SecurityConfig.java

package com.rixin.springsecuritydemo1.config;

import org.springframework.beans.factory.annotation.Autowired;
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.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    UserDetailsService userDetailsService;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
    }

    @Bean
    PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //自定义用户登录页面
        http.formLogin()
                .loginPage("/login.html") //登录页面设置
                .loginProcessingUrl("/user/login") //登录访问路径
                .defaultSuccessUrl("/test/index").permitAll() //登录成功后的跳转路径
                .and().authorizeRequests() //定义哪些url被保护,哪些不被保护
                    .antMatchers("/","/test/hello","/user/login").permitAll() //访问这些路径不需要认证
                    .antMatchers("/test/index").hasAuthority("admins") //当前登录用户,只有具有admins权限才可以访问这个路径
                .anyRequest().authenticated()
                .and().csrf().disable(); //关闭csrf防护

    }
}

MyUserDetailsService.java

package com.rixin.springsecuritydemo1.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.rixin.springsecuritydemo1.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
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.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.List;


@Service("userDetailsService")
public class MyUserDetailsService implements UserDetailsService {

    @Autowired
    UserMapper userMapper;

    @Override
    //s是表单传入的用户名
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {

        //查询数据库
        QueryWrapper<com.rixin.springsecuritydemo1.entity.User> wrapper = new QueryWrapper<>();
        wrapper.eq("username",s);
        com.rixin.springsecuritydemo1.entity.User user = userMapper.selectOne(wrapper);
        //判断
        if (user == null) {
            //认证失败
            throw new UsernameNotFoundException("用户名不存在!");
        }
        //授予用户权限
        List<GrantedAuthority> auths = AuthorityUtils.commaSeparatedStringToAuthorityList("admins");
        return new User(user.getUsername(), new BCryptPasswordEncoder().encode(user.getPassword()),auths);
    }
}

hasAnyAuthority

hasAnyAuthority方法:如果当前主体有任何提供的角色(给定的作为一个逗号分隔符的字符串列表)的话,返回true。

示例:
SecurityConfig.java

package com.rixin.springsecuritydemo1.config;

import org.springframework.beans.factory.annotation.Autowired;
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.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    UserDetailsService userDetailsService;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
    }

    @Bean
    PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //自定义用户登录页面
        http.formLogin()
                .loginPage("/login.html") //登录页面设置
                .loginProcessingUrl("/user/login") //登录访问路径
                .defaultSuccessUrl("/test/index").permitAll() //登录成功后的跳转路径
                .and().authorizeRequests() //定义哪些url被保护,哪些不被保护
                    .antMatchers("/","/test/hello","/user/login").permitAll() //访问这些路径不需要认证
                    //.antMatchers("/test/index").hasAuthority("admins") //当前登录用户,只有具有admins权限才可以访问这个路径
                    .antMatchers("/test/index").hasAnyAuthority("admins,manager")
                .anyRequest().authenticated()
                .and().csrf().disable(); //关闭csrf防护

    }
}

基于角色访问控制

hasRole

hasRole方法:如果用户具备给定角色就允许访问,否则出现403。如果当前主体具有指定的角色,就返回true。

示例:
SecurityConfig.java

package com.rixin.springsecuritydemo1.config;

import org.springframework.beans.factory.annotation.Autowired;
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.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    UserDetailsService userDetailsService;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
    }

    @Bean
    PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //自定义用户登录页面
        http.formLogin()
                .loginPage("/login.html") //登录页面设置
                .loginProcessingUrl("/user/login") //登录访问路径
                .defaultSuccessUrl("/test/index").permitAll() //登录成功后的跳转路径
                .and().authorizeRequests() //定义哪些url被保护,哪些不被保护
                    .antMatchers("/","/test/hello","/user/login").permitAll() //访问这些路径不需要认证
                    //.antMatchers("/test/index").hasAuthority("admins") //当前登录用户,只有具有admins权限才可以访问这个路径
                    //.antMatchers("/test/index").hasAnyAuthority("admins,manager")
                    .antMatchers("/test/hello").hasRole("sale")
                .anyRequest().authenticated()
                .and().csrf().disable(); //关闭csrf防护

    }
}

MyUserDetailsService.java

package com.rixin.springsecuritydemo1.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.rixin.springsecuritydemo1.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
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.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.List;


@Service("userDetailsService")
public class MyUserDetailsService implements UserDetailsService {

    @Autowired
    UserMapper userMapper;

    @Override
    //s是表单传入的用户名
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {

        //查询数据库
        QueryWrapper<com.rixin.springsecuritydemo1.entity.User> wrapper = new QueryWrapper<>();
        wrapper.eq("username",s);
        com.rixin.springsecuritydemo1.entity.User user = userMapper.selectOne(wrapper);
        //判断
        if (user == null) {
            //认证失败
            throw new UsernameNotFoundException("用户名不存在!");
        }
        //授予用户权限
        List<GrantedAuthority> auths = AuthorityUtils.commaSeparatedStringToAuthorityList("manager,ROLE_sale");
        return new User(user.getUsername(), new BCryptPasswordEncoder().encode(user.getPassword()),auths);
    }
}

hasAnyRole

hasRoleAnyRole方法:表示用户具备任何一个角色就可以访问。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值