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>
相关推荐
小马爱打代码15 天前
SpringSecurity框架核心组件详解
springsecurity
沿途欣赏i2 个月前
SpringSecurity剖析
springsecurity
筱顾大牛2 个月前
SpringSecurity实现登录功能实战!!!
spring boot·intellij-idea·登录·springsecurity
朝暮7823 个月前
SpringSecurity入门
spring boot·spring·springsecurity
Black_Cat_yyds3 个月前
SpringSecurity--DelegatingFilterProxy工作流程
filter·springsecurity
天启A3 个月前
微服务集成springsecurity实现认证
springsecurity·软件工程日报
冯宝宝^3 个月前
SpringSecurity通用权限管理系统
vue.js·人工智能·spring boot·spring·springsecurity
Black_Cat_yyds3 个月前
会话固定攻击
运维·安全·springsecurity
慕木兮人可5 个月前
SpringBoot2.0.x旧版集成Swagger UI报错Unable to infer base url...解决办法
java·spring boot·cas·springsecurity·swagger-ui