欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Spring Security在用户授权中自定义403页面

程序员文章站 2024-03-19 15:37:04
...

Spring Security中的用户授权的基础上修改:

添加语句:

//配置没有权限访问跳转自定义页面
http.exceptionHandling().accessDeniedPage("/unauth.html");

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.exceptionHandling().accessDeniedPage("/unauth.html");


        //自定义用户登录页面
        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")
                    .antMatchers("/test/hello").hasAnyRole("sale")
                .anyRequest().authenticated()
                .and().csrf().disable(); //关闭csrf防护

    }
}

页面:
unauth.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <h1>没有访问权限</h1>
</body>
</html>