我正在学习Spring Security。 无法保存已注册的用户(如果他至少是注册用户,因为我不知道)
WebSecurityConfig:
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/", "/registration").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.permitAll()
.and()
.logout()
.permitAll();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userService)
.passwordEncoder(NoOpPasswordEncoder.getInstance());
}
用户实体:
@Entity
@Getter
@Setter
@ToString
@EqualsAndHashCode(of = "id")
public class User implements UserDetails {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String username;
private String password;
@ElementCollection(targetClass = Role.class, fetch = FetchType.EAGER)
@CollectionTable(name = "user_role", joinColumns = @JoinColumn(name = "user_id"))
@Enumerated(EnumType.STRING)
Set<Role> roles;
...constructors
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
return getRoles();
}
@Override
public boolean isAccountNonExpired() {
return true;
}
@Override
public boolean isAccountNonLocked() {
return true;
}
@Override
public boolean isCredentialsNonExpired() {
return true;
}
@Override
public boolean isEnabled() {
return true;
}
}
控制器:
@GetMapping("/registration")
public String registration(){
return "registration";
}
@PostMapping("/registration")
public String addUser(User user, Map<String, Object> model) {
User userFromDb = userRepository.findByUsername(user.getUsername());
if (userFromDb != null) {
model.put("message", "User exists!");
return "registration";
}
user.setRoles(Collections.singleton(Role.USER));
userRepository.save(user);
return "redirect:/login";
胸腺: 你好:
<form th:action="@{/logout}" method="post">
<input type="submit" value="Sign Out"/>
</form>
登录:
<div th:if="${param.error}">
Invalid username and password.
</div>
<div th:if="${param.logout}">
You have been logged out.
</div>
<form th:action="@{/login}" method="post">
<div><label> User Name : <input type="text" name="username"/> </label></div>
<div><label> Password: <input type="password" name="password"/> </label></div>
<div><input type="submit" value="Sign In"/></div>
</form>
注册:
<form action="/login" method="post">
<div><label>User Name: <input type="text" name="username"></label></div>
<div><label>Password: <input type="text" name="username"></label></div>
<div><input type="submit" value="Sign in"></div>
</form>
<a href="/registration">Add new User</a>
我不知道要修复的位置(在表单的前端还是后端) 我的注册表完全是怎么回事,如何添加“保存用户”?
如果可能的话,我想知道,百里香/速冻/胡子之间的区别是什么,我必须使用哪种?
答案 0 :(得分:0)
//Register Mapping
@RequestMapping(value = "/registerUser", method = RequestMethod.POST)
public String registerPage(Registration reg,HttpSession session) {
RegisterUser exitingUser = service.findUserByEmail(reg.getEmail());
if (exitingUser == null) {
RegisterUser user = new RegisterUser ();
user.setEmail(reg.getEmail());
user.setPass(reg.getPass());
service.registerNewUserAccount(user);
}
}
// User Model
public class User extends BasicEntity {
/** */
private static final long serialVersionUID = 1L;
@ValidEmail
@Column(name = "EMAIL_ID", nullable = false)
private String email_id;
@Column(name = "PASSWORD", length = 60, nullable = false)
private String password;
@Column(name = "ENABLED")
private boolean enabled;
@OneToMany(mappedBy = "user", cascade = { CascadeType.ALL })
private Set<Privilege> privileges;
@Transient
private String matchingPassword;
@ManyToMany(fetch = FetchType.EAGER, cascade = { CascadeType.ALL })
@JoinTable(name = "USER_DETAILS_ROLE", joinColumns = @JoinColumn(name = "USER_ID", referencedColumnName = "ID"), inverseJoinColumns = @JoinColumn(name = "ROLE_ID", referencedColumnName = "ID"))
private Set<Role> roles;
public RegistrationDetails() {
super();
this.enabled = false;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPass() {
return pass;
}
public void setPass(String pass) {
this.pass = pass;
}
public boolean isEnabled() {
return enabled;
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
public String getMatchingPassword() {
return matchingPassword;
}
public void setMatchingPassword(String matchingPassword) {
this.matchingPassword = matchingPassword;
}
@JsonIgnore
public Set<Role> getRoles() {
return roles;
}
public void setRoles(Set<Role> roles) {
this.roles = roles;
}
@JsonIgnore
public Set<Privilege> getPermissions() {
return privileges;
}
public void setPermissions(Set<Privilege> privileges) {
this.privileges= privileges;
}
public static long getSerialversionuid() {
return serialVersionUID;
}
public Collection<? extends GrantedAuthority> getAuthorities(Collection<Role> roles) {
List<String> userRole = new ArrayList<String>();
for (Role role : roles) {
userRole.add(role.getName());
}
return getGrantedAuthorities(userRole);
}
private List<GrantedAuthority> getGrantedAuthorities(List<String> privileges) {
List<GrantedAuthority> authorities = new ArrayList<>();
for (String privilege : privileges) {
authorities.add(new SimpleGrantedAuthority(privilege));
}
return authorities;
}
//security config
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private UserDetailsService userDetailsService;
@Override
public void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().antMatchers("/","/resources/**", "/**").permitAll().anyRequest().authenticated().and().formLogin()
.loginPage("/").permitAll().usernameParameter("username").passwordParameter("password")
.loginProcessingUrl("/j_spring_security_check").failureUrl("/")
.successHandler(authenticationSuccessHandler()).and().logout().logoutSuccessUrl("/")
.logoutUrl("/logout").invalidateHttpSession(true).deleteCookies("JSESSIONID").and().csrf().disable().headers().frameOptions().sameOrigin();
}
@Override
protected void configure(final AuthenticationManagerBuilder auth) throws Exception {
auth.authenticationProvider(authenticationProvider());
}
@Bean
public DaoAuthenticationProvider authenticationProvider() {
DaoAuthenticationProvider authProvider = new DaoAuthenticationProvider();
authProvider.setUserDetailsService(userDetailsService);
authProvider.setPasswordEncoder(passwordEncoder());
return authProvider;
}
@Bean
public AuthenticationSuccessHandler authenticationSuccessHandler() {
return new AuthenticationSuccessHandler();
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder(11);
}
//希望这对您有帮助