当前位置: 首页> 财经> 创投人物 > 青岛品牌设计公司_电商b2b_营销型网站建设托管_网络营销品牌

青岛品牌设计公司_电商b2b_营销型网站建设托管_网络营销品牌

时间:2025/7/18 20:56:26来源:https://blog.csdn.net/ghx123456ghx/article/details/143025016 浏览次数:0次
青岛品牌设计公司_电商b2b_营销型网站建设托管_网络营销品牌

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

1 依赖

        <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配置

//开启方法级保护,如:@PreAuthorize("has Authority('ROLE_ADMIN')")
@EnableGlobalMethodSecurity(prePostEnabled = true)
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {@Autowiredpublic 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;}@Overrideprotected 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"后台

<!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>
关键字:青岛品牌设计公司_电商b2b_营销型网站建设托管_网络营销品牌

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

责任编辑: