一项目添加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 {
@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"后台
<!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>
本站资源均来自互联网,仅供研究学习,禁止违法使用和商用,产生法律纠纷本站概不负责!如果侵犯了您的权益请与我们联系!
转载请注明出处: 免费源码网-免费的源码资源网站 » springsecurity使用
发表评论 取消回复