分别写出例子
时间: 2023-08-12 19:23:49 浏览: 38
1. 基于表单的认证示例:
假设我们有一个登录页面,用户需要输入用户名和密码进行认证。在Spring Security中,我们可以使用formLogin()方法启用基于表单的认证。
```
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/login").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.defaultSuccessUrl("/home")
.permitAll()
.and()
.logout()
.permitAll();
}
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth
.inMemoryAuthentication()
.withUser("user").password("{noop}password").roles("USER");
}
}
```
在上面的示例中,我们使用了一个简单的用户名和密码进行认证。用户可以通过/login路径访问登录页面,登录成功后将跳转到/home路径。认证信息存储在内存中,并且只有一个用户“user”。
2. 基于HTTP Basic认证示例:
在Spring Security中,我们可以使用httpBasic()方法启用基于HTTP Basic的认证。下面是一个简单的示例:
```
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.anyRequest().authenticated()
.and()
.httpBasic();
}
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth
.inMemoryAuthentication()
.withUser("user").password("{noop}password").roles("USER");
}
}
```
在上面的示例中,我们启用了基于HTTP Basic的认证,并且在内存中存储了一个用户“user”。用户可以使用HTTP请求头部中的"Authorization"字段来进行认证。
3. 基于OAuth2认证示例:
下面是一个示例,使用Spring Security实现基于OAuth2的认证:
```
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.anyRequest().authenticated()
.and()
.oauth2Login();
}
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth
.inMemoryAuthentication()
.withUser("user").password("{noop}password").roles("USER");
}
}
```
在上面的示例中,我们使用了oauth2Login()方法启用了基于OAuth2的认证,并且在内存中存储了一个用户“user”。用户可以使用OAuth2协议进行认证,并且可以使用授权码、密码、客户端凭证等方式获取令牌。