我正在尝试使用Spring安全性保护Spring Boot Web应用程序的安全,但是在配置身份验证管理器时,我与级联方法感到困惑。目前,我正在使用内存数据库,该数据库具有表用户和填充有数据的权限。
任何人都可以解释这种用例配置身份验证机制的简便方法吗?
答案 0 :(得分:0)
为需要此服务的其他人造福。
要实现jdbcAuthentication,您需要向数据库表中写入两个查询
Query1: usersByUsernameQuery (设置用于根据用户名查找用户的查询。)
Query2 : authoritiesByUsernameQuery (设置用于根据用户名查找用户权限的查询。)
可能是Java配置或xml配置,您所需要做的就是
1.创建数据源
2.通过注入数据源依赖项并配置usersByUsernameQuery和AuthorityByUsernameQuery,在AuthenticationManagerBuilder
中配置jdbc身份验证。
3.配置HttpSecurity。下面提供了详细信息和默认值
-----配置这些URL的拦截URL模式和授权
Default role of unauthenticated user = ROLE_ANONYMOUS
-----配置表单登录以避免默认的登录屏幕和下面给出的默认行为。
login-page = "/login" with HTTP get
usernameParameter = "username"
passwordParameter = "password"
failureUrl = "/login?error"
loginProcessingUrl= "/login" with HTTP post
successUrl = "/"
-----配置注销以覆盖默认行为。
logoutUrl = "/logout"
logoutSuccessUrl = "/login?logout"
-----配置会话管理以覆盖默认行为
expiredUrl = "/login?expired"
invalidate-session = true //you can set false and use delete-cookies="JSESSIONID"
maximumSessions = The default is to allow any number of sessions for a users.
如果这不足以从我的github存储库下载。 Working copy of Spring security with Java configuration
@Configuration
@EnableWebSecurity
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter
{
public DataSource dataSource()
{
BasicDataSource dataSource = new BasicDataSource();
dataSource.setDriverClassName("com.mysql.jdbc.Driver");
dataSource.setUrl("jdbc:mysql://localhost:3306/springmvc");
dataSource.setUsername("root");
dataSource.setPassword("root");
dataSource.setInitialSize(2);
dataSource.setMaxActive(5);
return dataSource;
}
@Autowired
public void configAuthentication(AuthenticationManagerBuilder auth) throws Exception
{
auth.jdbcAuthentication().dataSource(dataSource()).passwordEncoder(passwordEncoder())
.usersByUsernameQuery("select username, password, enabled from userdetails where userName=?")
.authoritiesByUsernameQuery(
"select ud.username as username, rm.name as role from userdetails ud INNER JOIN rolemaster rm ON rm.id = ud.roleId where username = ?");
}
@Override
protected void configure(final HttpSecurity http) throws Exception
{
http
.authorizeRequests()
.antMatchers("/resources/**", "/", "/login", "/api/**").permitAll()
.antMatchers("/config/*", "/app/admin/*")
.hasRole("ADMIN")
.antMatchers("/app/user/*")
.hasAnyRole("ADMIN", "USER")
.and().exceptionHandling()
.accessDeniedPage("/403")
.and().formLogin()
.loginPage("/login")
.usernameParameter("userName").passwordParameter("password")
.defaultSuccessUrl("/app/user/dashboard")
.failureUrl("/login?error=true")
.and().logout()
.logoutSuccessHandler(new CustomLogoutSuccessHandler())
.invalidateHttpSession(true)
.and()
.csrf()
.disable();
http.sessionManagement().maximumSessions(1).expiredUrl("/login?expired=true");
}
@Bean
public PasswordEncoder passwordEncoder()
{
return new BCryptPasswordEncoder();
}
}
如果这不足以从我的github存储库下载。 Working copy of Spring security with XML configuration
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/security"
xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security.xsd">
<http auto-config="true" use-expressions="true" create-session="ifRequired">
<csrf disabled="true"/>
<intercept-url pattern="/resources/**" access="permitAll" />
<intercept-url pattern="/" access="permitAll" />
<intercept-url pattern="/login" access="permitAll" />
<intercept-url pattern="/api/**" access="permitAll" />
<intercept-url pattern="/config/*" access="hasRole('ROLE_ADMIN')" />
<intercept-url pattern="/app/admin/*" access="hasRole('ROLE_ADMIN')" />
<intercept-url pattern="/app/user/*" access="hasAnyRole('ROLE_USER', 'ROLE_ADMIN')" />
<access-denied-handler error-page="/403" />
<form-login
login-page="/login"
default-target-url="/app/user/dashboard"
authentication-failure-url="/login?error=true"
username-parameter="userName"
password-parameter="password" />
<logout invalidate-session="false" success-handler-ref="customLogoutSuccessHandler"/>
<session-management invalid-session-url="/login?expired=true">
<concurrency-control max-sessions="1" />
</session-management>
</http>
<authentication-manager>
<authentication-provider>
<password-encoder ref="encoder" />
<jdbc-user-service data-source-ref="dataSource"
users-by-username-query=
"select username, password, enabled from userdetails where userName=?"
authorities-by-username-query=
"select ud.username as username, rm.name as role from userdetails ud INNER JOIN rolemaster rm ON rm.id = ud.roleId where username = ?" />
</authentication-provider>
</authentication-manager>
<beans:bean id="encoder" class="org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder" />
<beans:bean id="customLogoutSuccessHandler" class="com.pvn.mvctiles.configuration.CustomLogoutSuccessHandler" />
<beans:bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
<beans:property name="driverClassName" value="com.mysql.jdbc.Driver" />
<beans:property name="url" value="jdbc:mysql://localhost:3306/springmvc" />
<beans:property name="username" value="root"/>
<beans:property name="password" value="root"/>
<beans:property name="initialSize" value="2" />
<beans:property name="maxActive" value="5" />
</beans:bean>
</beans:beans>
在这里您需要覆盖loadUserByUsername方法
1.通过在方法中作为争论传递的用户名从数据库中加载用户密码。
2.从数据库中为用户加载权限,并构造一个GrantedAuthority列表
3.通过传递在步骤1和步骤2中获取的密码和授权来创建用户
4.返回UserDetail对象,以便spring容器本身负责认证和授权。
@Component
public class UserDaoImpl implements UserDao, UserDetailsService
{
Logger OUT = LoggerFactory.getLogger(UserDaoImpl.class);
@Autowired
SessionFactory sessionFactory;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException
{
try (Session session = sessionFactory.openSession();)
{
CriteriaBuilder criteriaBuilder = session.getCriteriaBuilder();
CriteriaQuery<DbUserDetails> userCriteria = criteriaBuilder.createQuery(DbUserDetails.class);
Root<DbUserDetails> userRoot = userCriteria.from(DbUserDetails.class);
userCriteria.select(userRoot).where(criteriaBuilder.equal(userRoot.get("userName"), username));
Query<DbUserDetails> userQuery =session.createQuery(userCriteria);
DbUserDetails dbUser = userQuery.getSingleResult();
CriteriaQuery<RoleMaster> roleCriteria = criteriaBuilder.createQuery(RoleMaster.class);
Root<RoleMaster> roleRoot = roleCriteria.from(RoleMaster.class);
roleCriteria.select(roleRoot).where(criteriaBuilder.equal(roleRoot.get("id"), dbUser.getRoleId()));
Query<RoleMaster> roleQuery =session.createQuery(roleCriteria);
RoleMaster role = roleQuery.getSingleResult();
List<GrantedAuthority> authList = new ArrayList<>();
authList.add(new SimpleGrantedAuthority(role.getName()));
return new User(username, dbUser.getPassword(),true, true, true, true, authList);
}
catch (Exception e)
{
OUT.error("Exception - {}", e);
throw new UsernameNotFoundException("Exception caught", e);
}
}
}
@Configuration
@EnableWebSecurity
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter
{
@Autowired
UserDaoImpl userDaoImpl;
@Autowired
public void configureUserDetailsService(AuthenticationManagerBuilder auth) throws Exception
{
auth.userDetailsService(userDaoImpl);
}
...
}
答案 1 :(得分:-1)
最近,在学习Spring MVC时,我做到了。希望这会有所帮助!
LoginController.java
LoginController处理所有与登录相关的Web请求。它包含一个用于处理登录失败和注销请求的单一请求映射方法。由于请求映射方法返回一个名为login的视图,因此我们需要创建login.jsp。
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
@Controller
public class LoginController {
@RequestMapping(value = "/login", method = RequestMethod.GET)
public String login() {
return "login";
}
}
login.jsp
login.jsp中的重要标记。在这里,我们仅检查页面请求参数是否包含一个名为error的变量,如果包含则显示错误消息。 Similalry,用于注销和accessDenied。
<c:if test="${param.error != null}">
<div class="alert alert-danger">
<p>Invalid username and password.</p>
</div>
</c:if>
我们将登录表单值,用户名和密码发布到Spring安全认证处理程序UR,该处理程序存储在名为${loginUrl}
的变量中。这里的<c:url>
用于对URL进行编码。
<c:url var="loginUrl" value="/login" />
<form action="${loginUrl}" method="post" class="form-horizontal">
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="spring" uri="http://www.springframework.org/tags" %>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="x-ua-compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Products</title>
<link rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
</head>
<body>
<div class="container">
<div class="row">
<div class="col-md-4 col-md-offset-4">
<div class="panel panel-default">
<div class="panel-heading">
<h3 class="panel-title">Please sign in</h3>
</div>
<div class="panel-body">
<c:url var="loginUrl" value="/login" />
<form action="${loginUrl}" method="post" class="form-horizontal">
<c:if test="${param.error != null}">
<div class="alert alert-danger">
<p>Invalid username and password</p>
</div>
</c:if>
<c:if test="${param.logout != null}">
<div class="alert alert-success">
<p>You have been logged out successfully</p>
</div>
</c:if>
<c:if test="${param.accessDenied != null}">
<div class="alert alert-danger">
<p>Access Denied: You are not authorized</p>
</div>
</c:if>
<div class="input-group input-sm">
<label class="input-group-addon" for="userId">
<i class="fa fa-user"></i>
</label>
<input type="text" class="form-control" id="userId" name="userId"
placeholder="Enter username" required>
</div>
<div class="input-group input-sm">
<label class="input-group-addon" for="password">
<i class="fa fa-lock"></i>
</label>
<input type="password" class="form-control" id="password" name="password"
placeholder="Enter password" required>
</div>
<div class="form-actions">
<input type="submit" class="btn btn-block btn-primary btn-default"
value="Login">
</div>
</form>
</div>
</div>
</div>
</div>
</div>
</body>
</html>
SecurityConfig.java
我们创建了LoginController
来分发登录页面。我们需要告诉Spring如果用户试图在不登录的情况下访问该页面,则向用户展示此登录页面。为实现这一点,引入了WebSecurityConfigurerAdapter
类;通过扩展WebSecurityConfigurerAdapter
,我们可以为Web应用程序中与安全性相关的各种设置配置HttpSecurity
对象。因此,创建了SecurityConfig类来配置Web应用程序中与安全性相关的方面。
SecurityConfig
类中的重要方法之一是configureGlobalSecurity
;在这种方法下,我们只需配置AuthenticationManagerBuilder
来创建两个用户john
和admin
,并使用指定的密码和角色。
下一个重要的方法是configure
;在此方法中,我们正在进行一些与身份验证和授权相关的配置。
第一个配置告诉Spring MVC,如果需要身份验证,它应该将用户重定向到登录页面。这里的loginpage
属性表示应将请求转发到哪个URL以获取登录表单。 (请求路径应与login()
的{{1}}方法的请求映射相同。我们还在此配置中设置了用户名和密码参数名。
通过这种配置,在通过登录页面将用户名和密码发布到Spring Security认证处理程序时,Spring希望这些值分别绑定在变量名LoginController
和userId
下;这就是为什么用户名和密码的输入标签带有名称属性password
和userId
password
类似地,Spring在<input type="text" class="form-control" id="userId" name="userId"
placeholder="Enter Username" required>
<input type="password" class="form-control" id="password" name="password"
placeholder="Enter Password" required>
URL下处理注销操作。
接下来,我们配置默认的成功URL,它表示成功登录后的默认登录页面。类似地,失败URL指示在登录失败的情况下需要将请求转发到哪个URL。
/logout
我们正在将请求参数设置为失败URL中的错误;呈现登录页面时,如果登录失败,将显示错误消息“无效的用户名和密码”。同样,我们还可以配置注销成功URL,该URL指示注销后需要将请求转发到何处。
httpSecurity.formLogin().defaultSuccessUrl("/app/user/dashboard").failureUrl("/login?error");
下一个配置定义了哪个用户应该访问哪个页面。
httpSecurity.logout().logoutSuccessUrl("/login?logout");
Similarly, for accessDenied.
前面的配置为我们的网站定义了三个重要的授权规则 蚂蚁模式匹配器方面的应用。第一个允许请求网址 以/结尾,即使请求没有任何作用。如果请求具有ADMIN角色,则下一个规则允许所有以/ add结尾的请求URL。第三条规则允许所有具有/ app /路径的请求URL(如果它们具有USER角色)。
httpSecurity.authorizeRequests()
.antMatchers("/").permitAll()
.antMatchers("/**/add").access("hasRole('ADMIN')")
.antMatchers("/**/app/**").access("hasRole('USER')");
SecurityWebApplicationInitializer.java
在安全文件中定义了与安全相关的配置之后,Spring应该知道该配置文件,并且在启动应用程序之前必须先读取此配置文件。只有这样,它才能创建和管理那些与安全相关的
配置。为了在Spring启动期间拾取该文件,我们创建了import org.springframework.beans.factory.annotation.Autowired;
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;
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
public void configureGlobalSecurity(AuthenticationManagerBuilder managerBuilder) throws Exception {
managerBuilder.inMemoryAuthentication().withUser("john")
.password("{noop}pa55word").roles("USER");
managerBuilder.inMemoryAuthentication().withUser("admin")
.password("{noop}root123").roles("USER", "ADMIN");
}
@Override
protected void configure(HttpSecurity httpSecurity) throws Exception {
httpSecurity.formLogin().loginPage("/login").usernameParameter("userId")
.passwordParameter("password");
httpSecurity.formLogin().defaultSuccessUrl("/app/user/dashboard")
.failureUrl("/login?error");
httpSecurity.logout().logoutSuccessUrl("/login?logout");
httpSecurity.exceptionHandling().accessDeniedPage("/login?accessDenied");
httpSecurity.authorizeRequests().antMatchers("/").permitAll()
.antMatchers("/**/add").access("hasRole('ADMIN')")
.antMatchers("/**/app/**").access("hasRole('USER')");
httpSecurity.csrf().disable();
}
}
类,扩展了SecurityWebApplicationInitializer
类。
AbstractSecurityWebApplicationInitializer
somePage.jsp
import org.springframework.security.web.context.AbstractSecurityWebApplicationInitializer;
public class SecurityWebApplicationInitializer extends AbstractSecurityWebApplicationInitializer {
}