springsecurity使用

一项目添加springsecurity,保护方法不被调用,登录后可调用实现

1 依赖

c 复制代码
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>

2 springsecurity配置

c 复制代码
//开启方法级保护,如:@PreAuthorize("has Authority('ROLE_ADMIN')")
@EnableGlobalMethodSecurity(prePostEnabled = true)
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception{
        auth.userDetailsService(userDetailsService()).passwordEncoder(new BCryptPasswordEncoder());
    }
    public UserDetailsService userDetailsService(){
        InMemoryUserDetailsManager manager = new InMemoryUserDetailsManager();
        manager.createUser(User.withUsername("admin").password(new BCryptPasswordEncoder().encode("123")).roles("USER").build());
        return manager;
    }
    @Override
    protected void configure(HttpSecurity http) throws Exception{
        http.authorizeRequests()
                .antMatchers("/css/**","/index").permitAll()
                .antMatchers("/user/**").hasRole("USER")
                .antMatchers("/a").anonymous()
                .and()
                .formLogin().loginPage("/login").failureUrl("/login-error")
                .and()
                .exceptionHandling().accessDeniedPage("/401");
        http.logout().logoutSuccessUrl("/");
    }
}

3 登录跳转被保护页面流程

首先进入免登录的首页,当点击链接进入受到保护页面时,此时因没有登录,页面自动跳到登录页面,在登录页面输入有USER角色的账号时,自动跳到请求的href="/user/index"后台

c 复制代码
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>index</title>
</head>
<body>
  <p>这个页面没有受到保护</p>
  <p th:text="${tip}"></p>
  <form action="#" th:action="@{/logout}" method="post">
    <input type="submit" value="登出">
  </form>
<ul>
    <li>点击<a href="/user/index" th:href="@{/user/index}">跳转到user/index已被保护的界面</a></li>
</ul>
</body>
</html>
相关推荐
柯南二号5 天前
SpringSecurity 鉴权认证入门讲解
认证·鉴权·springsecurity
NiNg_1_2347 天前
SpringSecurity入门
后端·spring·springboot·springsecurity
北巷!!11 天前
SpringSecurity源码中核心类
源码·springsecurity
小马爱打代码1 个月前
SpringSecurity框架核心组件详解
springsecurity
沿途欣赏i2 个月前
SpringSecurity剖析
springsecurity
筱顾大牛3 个月前
SpringSecurity实现登录功能实战!!!
spring boot·intellij-idea·登录·springsecurity
朝暮7824 个月前
SpringSecurity入门
spring boot·spring·springsecurity
Black_Cat_yyds4 个月前
SpringSecurity--DelegatingFilterProxy工作流程
filter·springsecurity
天启A4 个月前
微服务集成springsecurity实现认证
springsecurity·软件工程日报