Java 为什么我能';t使用Jpa身份验证(Springboot、Jpa、Intellij、Postgres、thymeleaf)使用密码和用户名登录?
这是web安全的配置 我尝试使用数据库和密码登录(数据库中的Bcrypted存储),但登录重定向到错误页面,控制台中没有任何错误。我很困惑,请帮帮我Java 为什么我能';t使用Jpa身份验证(Springboot、Jpa、Intellij、Postgres、thymeleaf)使用密码和用户名登录?,java,authentication,spring-security,Java,Authentication,Spring Security,这是web安全的配置 我尝试使用数据库和密码登录(数据库中的Bcrypted存储),但登录重定向到错误页面,控制台中没有任何错误。我很困惑,请帮帮我 package com.example.spring_security_login_form.config; import com.example.spring_security_login_form.service.MyUserService; import org.springframework.beans.factory.annotatio
package com.example.spring_security_login_form.config;
import com.example.spring_security_login_form.service.MyUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import javax.sql.DataSource;
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private MyUserService myUserService;
@Autowired
DataSource dataSource;
@Bean
public BCryptPasswordEncoder passwordEncoder(){
BCryptPasswordEncoder bCryptPasswordEncoder= new BCryptPasswordEncoder();
return bCryptPasswordEncoder;
}
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth)throws Exception{
//cung cap user_service and password_encoder
auth.userDetailsService(myUserService).passwordEncoder(passwordEncoder());
}
public void configure(HttpSecurity http)throws Exception{
http.authorizeRequests().antMatchers( "/user").access("hasRole('USER')");
http.authorizeRequests().and().exceptionHandling().accessDeniedPage("/403");
http.authorizeRequests().and().formLogin().
loginProcessingUrl("/j_spring_security_login")
.loginPage("/login")
.defaultSuccessUrl("/user")
.failureUrl("/error")
.usernameParameter("username")
.passwordParameter("password")
.and().logout().logoutUrl("/j_spring_security_logout")
.logoutSuccessUrl("/login?logout");
}
}
UserController映射URL并将参数添加到模型中,该模型使用thymeleaf在HTML文件中使用
package com.example.spring_security_login_form.controller;
import com.example.spring_security_login_form.entity.GooglePojo;
import com.example.spring_security_login_form.entity.GoogleUtils;
import com.example.spring_security_login_form.entity.User;
import com.example.spring_security_login_form.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
@Controller
public class UserController {
@Autowired
private GoogleUtils googleUtils;
@Autowired
private BCryptPasswordEncoder encoder;
@Autowired
UserRepository userRepository;
@RequestMapping(value = {"/login", "/"})
public String login() {
return "login";
}
@RequestMapping("/login-google")
public String loginGoogle(HttpServletRequest request) throws IOException {
String code = request.getParameter("code");
if (code == null || code.isEmpty()) {
return "redirect:/login?error";
}
String accessToken =googleUtils.getToken(code);
GooglePojo googlePojo = googleUtils.getUserInfo(accessToken);
UserDetails userDetails = googleUtils.buildUser(googlePojo);
UsernamePasswordAuthenticationToken authenticationToken =new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
SecurityContextHolder.getContext().setAuthentication(authenticationToken);
return "redirect:/user";
}
@RequestMapping("/user")
public String user(){
return "user";
}
@RequestMapping("/sign-up")
public String signUp(Model model){
model.addAttribute("user", new User());
return "signUp";
}
@PostMapping("/signUp")
public String doSignUp(@ModelAttribute("User")User user, Model model){
user.setPassword(encoder.encode(user.getPassword()));
userRepository.save(user);
model.addAttribute("user", new User());
return "/login";
}
@RequestMapping("/403")
public String accessDenial(){
return "403";
}
}
UserDAO使用本机查询访问数据库中的数据,注释是Hibernate
package com.example.spring_security_login_form.dao;
import com.example.spring_security_login_form.entity.User;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;
import javax.persistence.EntityManagerFactory;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
@Repository(value = "userDAO")
public class UserDAO {
@Autowired
private EntityManagerFactory entityManagerFactory;
private SessionFactory sessionFactory;
//public User loadUserByName(final String username){
// sessionFactory = entityManagerFactory.unwrap(SessionFactory.class);
// List<User> users =new ArrayList<User>();
// Session session = sessionFactory.getCurrentSession();
// users =session.createQuery("from User where username=?1", User.class).setParameter(1, username).list();
// if(users.size()>0){
// return users.get(0);
// }else{
// return null;
// }
//}
@Autowired
private JdbcTemplate template;
public User loadUserByName(final String username) {
Connection conn = null;
PreparedStatement statement = null;
try {
// get connection
conn = template.getDataSource().getConnection();
conn.setAutoCommit(false);
// execute
statement = conn.prepareStatement("select id, user_name,pass_word,role from user_table where user_name = ?");
statement.setString(1, username);
ResultSet set = statement.executeQuery();
if (set.next()) {
User user = new User();
user.setId(set.getInt("id"));
user.setUsername(set.getString("user_name"));
user.setPassword(set.getString("pass_word"));
user.setRole(set.getString("role"));
return user;
}
return null ;
} catch (Exception e) {
return null;
}
}
}
login.html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Spring Boot Login </title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
<script src='https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js'></script>
<script src='https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js'></script>
<link href='https://use.fontawesome.com/releases/v5.8.1/css/all.css'>
<link rel="stylesheet" href='https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.1/css/all.min.css'>
<link rel="stylesheet" href="stylesheet.css">
</head>
<!--<body>-->
<!--<h2>Login with Google+ </h2>-->
<!--<a href="https://accounts.google.com/o/oauth2/auth?scope=email&redirect_uri=http://localhost:8090/login-google&response_type=code-->
<!-- &client_id=19662159820-916oumqdtc6g8fs9v5f2gketl9s7jnb1.apps.googleusercontent.com&approval_prompt=force">Login-->
<!-- with Gmail</a>-->
<!--<br/>-->
<!--<h2>Login with Facebook</h2>-->
<!--<a href="https://www.facebook.com/dialog/oauth?client_id=180439422588509&redirect_uri=https://localhost:8090/login-facebook">-->
<!-- Login with Facebook-->
<!--</a>-->
<!--<form name="login-form" th:action="@{/j_spring_security_login}" method="post">-->
<!-- <table>-->
<!-- <tr>-->
<!-- <td>Username:</td>-->
<!-- <td><input type="text" value="" name="username"></td>-->
<!-- </tr>-->
<!-- <tr>-->
<!-- <td>Password:</td>-->
<!-- <td><input type="password" value="" name="password"></td>-->
<!-- </tr>-->
<!-- <tr>-->
<!-- <td><input type="submit" value="Submit" name="submit"></td>-->
<!-- </tr>-->
<!-- </table>-->
<!-- -->
<div class="container">
<div class="row">
<div class="col-md-6 mx-auto py-4 px-0">
<div class="card p-0">
<div class="card-title text-center">
<h5 class="mt-5">HEY, THERE</h5> <small class="para">Login to your cool account below.</small>
</div>
<form class="signup" name="login-form" th:action="@{/j_spring_security_login}" method="post">
<div class="form-group"><input type="text" class="form-control" placeholder="Username"
name="username"></div>
<div class="form-group"><input type="password" class="form-control" placeholder="password"
name="password"></div>
<button type="submit" class="btn btn-primary" value="submit" name="submit">Login</button>
<div th:if="${param.error}" class="alert alert-danger">
Invalid username and password.
</div>
<div class="row">
<div class="col-6 col-sm-6"><a href="#">
<p class="text-left pt-2 ml-1">Forgot password?</p>
</a></div>
<!-- Sign up -->
<div class="col-6 col-sm-6"><a th:href="@{/sign-up}">
<p class="text-right pt-2 mr-1">Sign Up Now</p>
</a></div>
</div>
<span class="text-center">Or</span> <span class="text-center pt-3">Login Using</span>
<div class="row">
<div class="d-flex mx-auto pt-1 pb-3">
<a href="https://www.facebook.com/dialog/oauth?client_id=180439422588509&redirect_uri=https://localhost:8090/login-facebook"><i
class="fab fa-facebook"></i>Facebook</a>
<a href="https://accounts.google.com/o/oauth2/auth?scope=email&redirect_uri=https://localhost:8090/login-google&response_type=code&client_id=19662159820-916oumqdtc6g8fs9v5f2gketl9s7jnb1.apps.googleusercontent.com&approval_prompt=force">
<i class="fab fa-google"></i>Google</a>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
<input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}"/>
</form>
</body>
</html>
Spring启动登录
或使用
package com.example.spring_security_login_form.service;
import com.example.spring_security_login_form.dao.UserDAO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import javax.transaction.Transactional;
import java.util.Arrays;
@Service
@Transactional
public class MyUserService implements UserDetailsService {
@Autowired
private UserDAO userDAO;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
com.example.spring_security_login_form.entity.User user =userDAO.loadUserByName(username);
if(user==null){
throw new UsernameNotFoundException("Username not found");
}
boolean enabled = true;
boolean accountNonExpired = true;
boolean credentialsNonExpired =true;
boolean accountNonLocked = true;
return new User(username, user.getPassword(), enabled, accountNonExpired,
credentialsNonExpired, accountNonLocked, Arrays.asList(new SimpleGrantedAuthority(user.getRole())));
}
}
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Spring Boot Login </title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
<script src='https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js'></script>
<script src='https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js'></script>
<link href='https://use.fontawesome.com/releases/v5.8.1/css/all.css'>
<link rel="stylesheet" href='https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.1/css/all.min.css'>
<link rel="stylesheet" href="stylesheet.css">
</head>
<!--<body>-->
<!--<h2>Login with Google+ </h2>-->
<!--<a href="https://accounts.google.com/o/oauth2/auth?scope=email&redirect_uri=http://localhost:8090/login-google&response_type=code-->
<!-- &client_id=19662159820-916oumqdtc6g8fs9v5f2gketl9s7jnb1.apps.googleusercontent.com&approval_prompt=force">Login-->
<!-- with Gmail</a>-->
<!--<br/>-->
<!--<h2>Login with Facebook</h2>-->
<!--<a href="https://www.facebook.com/dialog/oauth?client_id=180439422588509&redirect_uri=https://localhost:8090/login-facebook">-->
<!-- Login with Facebook-->
<!--</a>-->
<!--<form name="login-form" th:action="@{/j_spring_security_login}" method="post">-->
<!-- <table>-->
<!-- <tr>-->
<!-- <td>Username:</td>-->
<!-- <td><input type="text" value="" name="username"></td>-->
<!-- </tr>-->
<!-- <tr>-->
<!-- <td>Password:</td>-->
<!-- <td><input type="password" value="" name="password"></td>-->
<!-- </tr>-->
<!-- <tr>-->
<!-- <td><input type="submit" value="Submit" name="submit"></td>-->
<!-- </tr>-->
<!-- </table>-->
<!-- -->
<div class="container">
<div class="row">
<div class="col-md-6 mx-auto py-4 px-0">
<div class="card p-0">
<div class="card-title text-center">
<h5 class="mt-5">HEY, THERE</h5> <small class="para">Login to your cool account below.</small>
</div>
<form class="signup" name="login-form" th:action="@{/j_spring_security_login}" method="post">
<div class="form-group"><input type="text" class="form-control" placeholder="Username"
name="username"></div>
<div class="form-group"><input type="password" class="form-control" placeholder="password"
name="password"></div>
<button type="submit" class="btn btn-primary" value="submit" name="submit">Login</button>
<div th:if="${param.error}" class="alert alert-danger">
Invalid username and password.
</div>
<div class="row">
<div class="col-6 col-sm-6"><a href="#">
<p class="text-left pt-2 ml-1">Forgot password?</p>
</a></div>
<!-- Sign up -->
<div class="col-6 col-sm-6"><a th:href="@{/sign-up}">
<p class="text-right pt-2 mr-1">Sign Up Now</p>
</a></div>
</div>
<span class="text-center">Or</span> <span class="text-center pt-3">Login Using</span>
<div class="row">
<div class="d-flex mx-auto pt-1 pb-3">
<a href="https://www.facebook.com/dialog/oauth?client_id=180439422588509&redirect_uri=https://localhost:8090/login-facebook"><i
class="fab fa-facebook"></i>Facebook</a>
<a href="https://accounts.google.com/o/oauth2/auth?scope=email&redirect_uri=https://localhost:8090/login-google&response_type=code&client_id=19662159820-916oumqdtc6g8fs9v5f2gketl9s7jnb1.apps.googleusercontent.com&approval_prompt=force">
<i class="fab fa-google"></i>Google</a>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
<input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}"/>
</form>
</body>
</html>