【Java】权限控制与安全认证(2)

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.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
// 自定义表单登录
http.formLogin()
.loginPage(“/backstage/admin_login”) // 自定义登录页面
.usernameParameter(“username”) // 指定登录表单中用于输入用户名的表单字段名
.passwordParameter(“password”) // 指定登录表单中用于输入密码的表单字段名
.loginProcessingUrl(“/backstage/admin/login”) // 表单提交的URL路径
.successForwardUrl(“/backstage/index”) // 登录成功后的跳转页面
.failureForwardUrl(“/backstage/admin_fail”); // 登录失败后的跳转页面

    // 权限拦截配置
    http.authorizeRequests()
            .antMatchers("/backstage/admin/login").permitAll() // 登录表单提交不需要认证
            .antMatchers("/backstage/admin\_fail").permitAll() // 登录失败页面不需要认证
            .antMatchers("/backstage/admin\_login").permitAll() // 登录页面不需要认证
            .antMatchers("/\*\*/\*.css", "/\*\*/\*.js").permitAll() // 静态资源放行
            .antMatchers("/backstage/\*\*").authenticated();

    // 退出登录
    http.logout()
            .logoutUrl("/backstage/admin/logout") // 退出登录路径
            .logoutSuccessUrl("/backstage/admin\_login") // 退出登录成功后跳转的页面
            .clearAuthentication(true) // 退出成功后清楚认证信息
            .invalidateHttpSession(true); // 退出成功后清除session

    // 异常处理
    http.exceptionHandling()
            .accessDeniedHandler(new MyAccessDeniedHandler()); // 权限不足处理器

    // 关闭csrf防护
    http.csrf().disable();

    // 开启跨域访问
    http.cors();

    super.configure(http);
}

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

}


###### MyUserDetailService



package com.nuc.travel.security;

import com.nuc.travel.pojo.Admin;
import com.nuc.travel.pojo.Permission;
import com.nuc.travel.service.AdminService;
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.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.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

// 自定义认证授权逻辑
@Service
public class MyUserDetailService implements UserDetailsService {
@Autowired
private AdminService adminService;

@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
    // 1、认证
    Admin admin = adminService.findByAdminName(username);
    if (admin == null) {
        throw new UsernameNotFoundException("用户不存在");
    }
    if (!admin.isStatus()) {
        throw new UsernameNotFoundException("用户不可用");
    }

    // 2、授权
    List<Permission> permissions = adminService.findAllPermission(username);
    List<GrantedAuthority> grantedAuthorities = new ArrayList();
    for (Permission permission : permissions) {
        grantedAuthorities.add(new SimpleGrantedAuthority(permission.getPermissionDesc()));
    }


    // 3、封装成UserDetails对象
    UserDetails userDetails = User.withUsername(admin.getUsername())
            .password(admin.getPassword())
            .authorities(grantedAuthorities)
            .build();
    return userDetails;
}

}


###### MyAccessDeniedHandler



package com.nuc.travel.security;

import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

// 自定义权限不足处理器
public class MyAccessDeniedHandler implements AccessDeniedHandler {

最后

自我介绍一下,小编13年上海交大毕业,曾经在小公司待过,也去过华为、OPPO等大厂,18年进入阿里一直到现在。

深知大多数网络安全工程师,想要提升技能,往往是自己摸索成长,但自己不成体系的自学效果低效又漫长,而且极易碰到天花板技术停滞不前!

因此收集整理了一份《2024年网络安全全套学习资料》,初衷也很简单,就是希望能够帮助到想自学提升又不知道该从何学起的朋友。

img

img

img

img

img

既有适合小白学习的零基础资料,也有适合3年以上经验的小伙伴深入学习提升的进阶课程,基本涵盖了95%以上网络安全知识点!真正的体系化!

如果你觉得这些内容对你有帮助,需要这份全套学习资料的朋友可以戳我获取!!

由于文件比较大,这里只是将部分目录截图出来,每个节点里面都包含大厂面经、学习笔记、源码讲义、实战项目、讲解视频,并且会持续更新!

如果你觉得这些内容对你有帮助,需要这份全套学习资料的朋友可以戳我获取!!

由于文件比较大,这里只是将部分目录截图出来,每个节点里面都包含大厂面经、学习笔记、源码讲义、实战项目、讲解视频,并且会持续更新!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值