【08】Spring Security登录授权和权限控制。

1.引入依赖

        <!--权限控制-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>

2.编写SecurityConfiguration配置类

package com.itheima.config;

import com.itheima.controller.backend.security.SpringSecurityUserService;
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.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;


/**
 * Security配置类
 */
@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

    /**
     * http请求处理方法
     *
     * @param http
     * @throws Exception
     */
    //授权
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        // 开启表单认证
        http.formLogin()
                // 自定义登录页面
                .loginPage("/backend/login.html")
                // 登录访问的url
                .loginProcessingUrl("/login")
                // 修改自定义表单name值.
                .usernameParameter("username").passwordParameter("password")
                // 登录成功后跳转路径
                .defaultSuccessUrl("/backend/pages/main.html")
                // 配置要控制的http URL---认证请求
                .and().authorizeRequests()
                //允许匿名访问的
                .antMatchers("/backend/login.html", "/backend/css/**", "/backend/img/**", "/backend/js/**", "/backend/plugins/**", "/favicon.ico").permitAll()
                //所有请求都需要登录认证才能访问;
                .anyRequest().authenticated();
        // 关闭csrf防护
        http.csrf().disable();
        // 允许iframe加载页面
        http.headers().frameOptions().sameOrigin();
        //注销,开启注销功能
        http.logout();
        http.rememberMe();
    }
    //认证用户
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(securityUserService).passwordEncoder(myPasswordEncoder());
    }
    @Autowired
    private SpringSecurityUserService securityUserService;
    @Bean
    protected PasswordEncoder myPasswordEncoder() {
        return new BCryptPasswordEncoder();
    }

}

3.创建一个类实现UserDetailsService接口,重写其中的方法。

根据用户名从数据库中查询用户信息。封装用户-角色-权限

package com.itheima.controller.backend.security;

import com.itheima.pojo.Permission;
import com.itheima.pojo.Role;
import com.itheima.pojo.User;
import com.itheima.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
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 java.util.ArrayList;
import java.util.List;
import java.util.Set;

@Service
public class SpringSecurityUserService implements UserDetailsService {
    //查找服务,实现查询数据库
    @Autowired
    private UserService userService;

    //根据用户名查询数据库中用户信息
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = userService.findByUsername(username);
        if(user == null){
            //用户名不存在
            return null;
        }
        List<GrantedAuthority> list = new ArrayList<>();
        //动态为当前用户授权
        Set<Role> roles = user.getRoles();
        for (Role role : roles) {
            //授予角色·
            list.add(new SimpleGrantedAuthority(role.getKeyword()));
            Set<Permission> permissions = role.getPermissions();
            for (Permission permission : permissions) {
                //授权
                list.add(new SimpleGrantedAuthority(permission.getKeyword()));
            }
        }
        org.springframework.security.core.userdetails.User securityUser =
                new org.springframework.security.core.userdetails.User(username,user.getPassword(),list);
        return securityUser;
    }
}

userService.findByUsername方法

package com.itheima.service.serviceImpl;

import com.itheima.dao.PermissionDao;
import com.itheima.dao.RoleDao;
import com.itheima.dao.UserDao;
import com.itheima.pojo.Permission;
import com.itheima.pojo.Role;
import com.itheima.pojo.User;
import com.itheima.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Set;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserDao userDao;
    @Autowired
    private RoleDao roleDao;
    @Autowired
    private PermissionDao permissionDao;

    /**
     * 根据用户名称查询用户信息和角色信息、权限信息
     * @param username
     * @return
     */
    @Transactional
    @Override
    public User findByUsername(String username) {
        //查询用户信息
        User user = userDao.findByUsername(username);
        if(user == null){
            return null;
        }

        Integer userId = user.getId();
        //根据用户Id查询用户角色
       Set<Role> roles =  roleDao.findByUserid(userId);
       //根据角色查询对应的权限
        for (Role role : roles) {
            Integer roleId = role.getId();
            //根据角色id查找对应的角色
            Set<Permission> permissions = permissionDao.findByRoleid(roleId);
            //为角色设置权限
            role.setPermissions(permissions);
        }
        //为用户设置角色
        user.setRoles(roles);
        return user;
    }
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值