spring security认证代码
时间: 2023-05-26 19:04:36 浏览: 173
Spring security认证两类用户代码实例
抱歉,作为语言模型AI,无法提供感性的代码,以下是供参考的spring security认证流程:
1. 配置spring security
在spring的xml配置文件中添加如下配置:
```xml
<security:http auto-config="true" use-expressions="true">
<security:intercept-url pattern="/admin/**" access="hasRole('ROLE_ADMIN')"/>
<security:form-login login-page="/login" default-target-url="/home"
authentication-failure-url="/login?error" username-parameter="username"
password-parameter="password"/>
<security:logout logout-success-url="/login?logout"/>
<security:csrf/>
</security:http>
```
2. 实现UserDetailsService接口
```java
@Service
public class MyUserDetailsService implements UserDetailsService {
@Autowired
private UserDao userDao;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
User user = userDao.findByUsername(username);
if (user == null) {
throw new UsernameNotFoundException("User not found");
}
return new org.springframework.security.core.userdetails.User(user.getUsername(), user.getPassword(),
getAuthorities(user));
}
private static Collection<? extends GrantedAuthority> getAuthorities(User user) {
List<GrantedAuthority> authorities = new ArrayList<>();
for (Role role : user.getRoles()) {
authorities.add(new SimpleGrantedAuthority(role.getName()));
}
return authorities;
}
}
```
3. 实现UserDetails接口
```java
@Entity
@Table(name = "users")
public class User implements UserDetails {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
private String username;
private String password;
@ManyToMany(fetch = FetchType.EAGER)
@JoinTable(
name = "users_roles",
joinColumns = @JoinColumn(
name = "user_id", referencedColumnName = "id"),
inverseJoinColumns = @JoinColumn(
name = "role_id", referencedColumnName = "id"))
private Set<Role> roles;
// 省略 getter 和 setter 方法
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
return roles.stream()
.map(role -> new SimpleGrantedAuthority(role.getName()))
.collect(Collectors.toList());
}
@Override
public boolean isAccountNonExpired() {
return true;
}
@Override
public boolean isAccountNonLocked() {
return true;
}
@Override
public boolean isCredentialsNonExpired() {
return true;
}
@Override
public boolean isEnabled() {
return true;
}
}
```
4. 配置web.xml
```xml
<!-- Spring Security -->
<filter>
<filter-name>springSecurityFilterChain</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
<filter-name>springSecurityFilterChain</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
```
5. 认证流程
用户通过表单提交用户名和密码,spring security根据用户名调用MyUserDetailsService的loadUserByUsername方法获取用户信息,然后将用户信息和表单提交的密码进行比对,如果匹配,认证通过,否则认证失败。
6. 认证成功后处理
当认证成功后,spring security会将用户信息存储在SecurityContextHolder中,并将请求重定向到用户请求的页面或默认页面。
7. 登出流程
用户点击退出链接,spring security将清除SecurityContextHolder中的认证信息,并将请求重定向到登录页面。
阅读全文