Spring Security身份认证和权限控制代码
时间: 2023-04-10 20:03:05 浏览: 109
spring-security代码
Spring Security身份认证和权限控制代码可以通过配置文件或者Java代码实现。其中,配置文件方式需要在Spring配置文件中添加如下代码:
```
<security:http auto-config="true" use-expressions="true">
<security:intercept-url pattern="/admin/**" access="hasRole('ROLE_ADMIN')" />
<security:intercept-url pattern="/user/**" access="hasRole('ROLE_USER')" />
<security:form-login login-page="/login" default-target-url="/home" authentication-failure-url="/login?error" />
<security:logout logout-success-url="/login?logout" />
</security:http>
<security:authentication-manager>
<security:authentication-provider>
<security:user-service>
<security:user name="admin" password="admin" authorities="ROLE_ADMIN" />
<security:user name="user" password="user" authorities="ROLE_USER" />
</security:user-service>
</security:authentication-provider>
</security:authentication-manager>
```
在Java代码中,可以通过继承WebSecurityConfigurerAdapter类来实现身份认证和权限控制,示例代码如下:
```
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
.withUser("admin").password("admin").roles("ADMIN")
.and()
.withUser("user").password("user").roles("USER");
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/admin/**").hasRole("ADMIN")
.antMatchers("/user/**").hasRole("USER")
.and()
.formLogin()
.loginPage("/login")
.defaultSuccessUrl("/home")
.failureUrl("/login?error")
.and()
.logout()
.logoutSuccessUrl("/login?logout");
}
}
```
以上是Spring Security身份认证和权限控制的代码示例。
阅读全文