玩转SpringBoot安全管理:SpringSecurity之自定义用户授权管理

玩转SpringBoot安全管理第三期来喽💨
前两期传送门:
💫玩转SpringBoot安全管理:SpringSecurity介绍及入门、自定义用户认证及授权管理、MVC Security安全配置介绍(内存和JDBC身份认证实现)
💫玩转SpringBoot安全管理:SpringSecurity之UserDetailService身份认证
资源也在前两期里有链接🔗

依旧回到WebSecurityConfigurerAdapter类当中,这次我们需要实现它的configure(HttpSecurity http)方法,在这个方法中我们实现用户访问控制
在开始之前呢,我们要把templates下的index.html页面改成下面的页面:
其实也就是把sec:authorize="hasRole(‘common’)"和sec:authorize="hasAuthority(‘ROLE_vip’)"给注释掉了,现在已经不需要用到他了,我们要自定义访问控制路径

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org" xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity5">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>影视直播厅</title>
</head>
<body>
<h1 align="center">欢迎进入电影网站首页</h1>
<div sec:authorize="isAnonymous()">
    <h2 align="center">游客您好,如果想查看电影<a th:href="@{/userLogin}">请登录</a></h2>
</div>
<div sec:authorize="isAuthenticated()">
    <h2 align="center"><span sec:authentication="name" style="color: #007bff"></span>您好,您的用户权限为
        <span sec:authentication="principal.authorities" style="color:darkkhaki"></span>,您有权观看以下电影</h2>
    <form th:action="@{/mylogout}" method="post">
        <input th:type="submit" th:value="注销" />
    </form>
</div>
<hr>
<!--sec:authorize="hasRole('common')"-->
<div >
    <h3>普通电影</h3>
    <ul>
        <li><a th:href="@{/detail/common/1}">飞驰人生</a></li>
        <li><a th:href="@{/detail/common/2}">夏洛特烦恼</a></li>
    </ul>
</div>
<!--sec:authorize="hasAuthority('ROLE_vip')"-->
<div >
    <h3>VIP专享</h3>
    <ul>
        <li><a th:href="@{/detail/vip/1}">速度与激情</a></li>
        <li><a th:href="@{/detail/vip/2}">猩球崛起</a></li>
    </ul>
</div>
</body>
</html>

SecurityConfig.java

package com.security.config;

import com.security.service.UserDetailsServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.authentication.configurers.provisioning.InMemoryUserDetailsManagerConfigurer;
import org.springframework.security.config.annotation.authentication.configurers.provisioning.JdbcUserDetailsManagerConfigurer;
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.crypto.bcrypt.BCryptPasswordEncoder;

import javax.sql.DataSource;

/**
 * @program: spring security
 * @description: security配置类
 * @author: xmonster_大魔王
 * @create: 2022-08-02 11:41
 **/
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Qualifier("dataSource")
    @Autowired
    private DataSource dataSource;

    @Autowired
    private UserDetailsServiceImpl userDetailsService;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {

//        设置密码编码器
        BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();    auth.userDetailsService(userDetailsService).passwordEncoder(bCryptPasswordEncoder);

    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests().antMatchers("/").permitAll()
                .antMatchers("/detail/common/**").hasRole("common")
                .antMatchers("/detail/vip/**").hasRole("vip")
                .anyRequest().authenticated()
                .and().formLogin();
    }
}

解析一下上方代码:
放行"/“请求”/detail/common/**",则需要common权限,vip也是一样的道理
.anyRequest().authenticated()的意思是:除了上面的印射地址以外,需要访问其他的页面都是需要登录的
.formLogin():配置了security默认的登录页面

测试

访问:http://localhost:8080/
在这里插入图片描述
点击下方的电影,举个例子,点击夏洛特烦恼:
可以看到,会自动跳转到登录界面
在这里插入图片描述
输入正确的并且具备能够观看夏洛特烦恼的用户
在这里插入图片描述
可以看到自动跳转到夏洛特烦恼的电影详情页面
再回到电影首页,可以看到它会自动获取当前登录用户信息:
在这里插入图片描述
如果现在点击查看vip电影,则会:
在这里插入图片描述
会报403错误,表示没有这个权限

  • 4
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
Spring Security是一个用于在Java应用程序中实现身份验证和授权的框架。它提供了一种可靠和灵活的方法来管理应用程序中的权限。通过使用Spring Security,可以轻松地自定义登录授权过程。 首先,我们需要创建一个实现`UserDetailsService`接口的类来处理用户的身份验证。在这个类中,我们可以自定义用户的登录逻辑,例如验证用户名和密码。我们可以使用Spring Security提供的各种验证方法来验证用户的身份。 接下来,我们需要配置Spring Security来处理用户授权。可以使用`WebSecurityConfigurerAdapter`类扩展一个配置类,并覆盖其中的`configure`方法。在这个方法中,我们可以指定哪些URL需要受到保护,哪些URL可以公开访问。例如,我们可以使用`antMatchers`方法来指定URL模式,然后使用`hasAuthority`或`hasRole`方法来指定用户需要具备的权限或角色。 另外,我们还可以使用`@PreAuthorize`注解来在方法级别上进行授权。可以在需要进行授权的方法上添加该注解,并指定用户需要具备的权限或角色。 最后,我们还可以通过自定义`AuthenticationProvider`来实现更复杂的授权逻辑。可以创建一个实现该接口的类,并在其中实现自定义的身份验证和授权逻辑。然后可以将这个自定义的`AuthenticationProvider`添加到Spring Security的配置中。 通过以上的方法,我们可以灵活地自定义登录授权过程。Spring Security提供了丰富的配置选项和接口来满足各种不同的授权需求。使用Spring Security,我们可以有效地管理应用程序中的权限,并确保只有具备合适权限的用户可以访问受保护的资源。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

我是X大魔王

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值