Я пытался заполучить Spring Security для существующего веб-приложения на Джерси.
У меня есть пользовательская страница входа с action="../login"
.
Всякий раз, когда я вхожу в учетные данныеи логин возвращается HTTP 403 Forbidden
. Я прошел через несколько вопросов о переполнении стека, на большинство из которых есть ответ, поскольку роли должны быть "ROLE_ {ROLE_NAME}", что и есть у меня. Также я попытался дать access="permitAll"
, который, похоже, тоже не работает.
Вопросы:
- Я не вижу никаких журналов от настроенного провайдера Custom AuthenticationProvider. Поэтому я сомневаюсь, что конфигурация провайдера аутентификации работает. Как это исправить?
- Как включить журналы безопасности Spring? У меня есть строки ниже в
application.properties
, но я не вижу никаких журналов. Есть ли что-то еще, что мне нужно для включения журналов?
logging.level.org.springframework.security=DEBUG
logging.level.org.springframework.webmvc=DEBUG
logging.level.org.springframework.web=DEBUG
Build.gradle
plugins{
id 'war'
id "io.spring.dependency-management" version "1.0.6.RELEASE"
}
webAppDirName = 'WebContent'
repositories {
mavenCentral()
}
dependencyManagement {
imports {
mavenBom 'org.springframework.security:spring-security-bom:5.2.1.RELEASE'
mavenBom 'org.springframework:spring-framework-bom:5.2.1.RELEASE'
}
}
dependencies {
...
compile "org.springframework.security:spring-security-web"
compile "org.springframework.security:spring-security-config"
compile "org.springframework:spring-webmvc"
}
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
id="WebApp_ID" version="3.0">
<display-name>User Management</display-name>
<welcome-file-list>
<welcome-file>/publisher/login.html</welcome-file>
</welcome-file-list>
...
<!-- Spring Configurations -->
<!-- Loads the Spring configurations from contextConfigLocation -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- The locations of the Spring Configuration. In this case, all configuration
is in /WEB-INF/spring/ -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring/*.xml</param-value>
</context-param>
<!-- DelegatingFilterProxy looks for a Spring bean by the name of filter
(springSecurityFilterChain) and delegates all work to that Bean. This is
how the Servlet Container can a Spring Bean to act as a Servlet Filter. -->
<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>
</web-app>
webContent / WEB-INF / spring / security.xml
<b:beans xmlns="http://www.springframework.org/schema/security"
xmlns:b="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/security https://www.springframework.org/schema/security/spring-security.xsd">
<http authentication-manager-ref="authenticationManager" use-expressions="true">
<intercept-url pattern="/publisher/login.html" access="permitAll" />
<intercept-url pattern="/login" access="permitAll" />
<form-login login-page="/publisher/login.html"
login-processing-url="/login"
default-target-url="/home.html"
username-parameter="username" password-parameter="password"
always-use-default-target="true"
authentication-failure-url="/prelogout.html" />
<intercept-url pattern="/publisher/css/*" access="permitAll" />
<intercept-url pattern="/publisher/images/*" access="permitAll" />
<intercept-url pattern="/publisher/js/*" access="permitAll" />
<intercept-url pattern="/publisher/scripts/*" access="permitAll" />
<intercept-url pattern="/publisher/semantic/*" access="permitAll" />
</http>
<b:bean id="customAuthenticationProvider" class="com.example.user.AuthenticationDAOImpl" />
<authentication-manager id="authenticationManager" alias="authenticationManager">
<authentication-provider ref="customAuthenticationProvider" />
</authentication-manager>
</b:beans>
AuthenticationDAOImpl.java
package com.example.user;
@Component
public class AuthenticationDAOImpl implements AuthenticationProvider {
static Logger log = Logger.getLogger(AuthenticationDAOImpl.class.getName());
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
if (log.isDebugEnabled()) {
log.debug("AuthenticationDAOImpl : begin with authenticationName : "+authentication.getName());
}
String isLdapEnabled = StartupServlet.isLdapEnabledFlag;
if(isLdapEnabled.equalsIgnoreCase("false")){
if( (null == authentication.getPrincipal() || (null != authentication.getPrincipal() && authentication.getPrincipal().toString().equalsIgnoreCase(""))) ||
(null == authentication.getCredentials() || (null!=authentication.getCredentials() && authentication.getCredentials().toString().equalsIgnoreCase("")))){
throw new BadCredentialsException("Invalid username/password");
}
}
String username = (String)authentication.getPrincipal();
String password = (String)authentication.getCredentials();
List<SimpleGrantedAuthority> authorities = new ArrayList<SimpleGrantedAuthority>();
String[] userArr = null;
if(username.contains("~~")){
userArr = username.split("~~");
}
Connection conn = null;
try {
if(userArr != null){
//if(userArr.length == 3){
String name = userArr[0];
String domainName = userArr[1];
String consDomainName = "";
if(userArr.length == 3){
consDomainName = userArr[2];
}
LoginDao loginDao = new LoginDao();
if (log.isInfoEnabled()) {
log.info("AuthenticationDAOImpl :" + Constants.LOG_CONNECTION_OPEN);
}
conn = MySqlDBConnection.getInstance().getMySqlConnection();
conn.setAutoCommit(false);
User user = loginDao.getUserByUserCredentials(domainName, consDomainName, name,
password,conn);
if (user == null) {
if(userArr.length == 3){
if(isLDAPUser(domainName, consDomainName, name, conn)) {
if(isLdapEnabled.equalsIgnoreCase("true") && BehaviouralConstants.isLdapUserLockOutEnabled) {
loginDao.updateFailAttemptsForDevPortal(domainName, consDomainName, name, "reqID");
}
} else {
loginDao.updateFailAttemptsForDevPortal(domainName, consDomainName, name, "reqID");
}
} else {
if(isLDAPUser(domainName, consDomainName, name, conn)) {
if(isLdapEnabled.equalsIgnoreCase("true") && BehaviouralConstants.isLdapUserLockOutEnabled) {
loginDao.updateFailAttemptsForPubPortal(domainName, name);
}
} else {
loginDao.updateFailAttemptsForPubPortal(domainName,name);
}
}
throw new BadCredentialsException("Invalid username/password");
} else {
if(null != password && user.getAccountLockFlag() == 0){
if (user.getRole().equalsIgnoreCase("admin")) {
authorities.add(new SimpleGrantedAuthority("ROLE_ADMIN"));
} else if (user.getRole().equalsIgnoreCase("technical")) {
authorities.add(new SimpleGrantedAuthority("ROLE_TECHNICAL"));
} else if (user.getRole().equalsIgnoreCase("business")) {
authorities.add(new SimpleGrantedAuthority("ROLE_BUSINESS"));
} else if (user.getRole().equalsIgnoreCase("approver")) {
authorities.add(new SimpleGrantedAuthority("ROLE_APPROVER"));
} else {
if(userArr.length == 3){
if(isLDAPUser(domainName, consDomainName, name, conn)) {
if(isLdapEnabled.equalsIgnoreCase("true") && BehaviouralConstants.isLdapUserLockOutEnabled) {
loginDao.updateFailAttemptsForDevPortal(domainName, consDomainName, name, "reqID");
}
} else {
loginDao.updateFailAttemptsForDevPortal(domainName, consDomainName, name, "reqID");
}
} else {
if(isLDAPUser(domainName, consDomainName, name, conn)) {
if(isLdapEnabled.equalsIgnoreCase("true") && BehaviouralConstants.isLdapUserLockOutEnabled) {
loginDao.updateFailAttemptsForPubPortal(domainName, name);
}
} else {
loginDao.updateFailAttemptsForPubPortal(domainName,name);
}
}
throw new BadCredentialsException(
"Invalid username/password");
}
}else{
if(userArr.length == 3){
if(isLDAPUser(domainName, consDomainName, name, conn)) {
if(isLdapEnabled.equalsIgnoreCase("true") && BehaviouralConstants.isLdapUserLockOutEnabled) {
loginDao.updateFailAttemptsForDevPortal(domainName, consDomainName, name, "reqID");
}
} else {
loginDao.updateFailAttemptsForDevPortal(domainName, consDomainName, name, "reqID");
}
} else {
if(isLDAPUser(domainName, consDomainName, name, conn)) {
if(isLdapEnabled.equalsIgnoreCase("true") && BehaviouralConstants.isLdapUserLockOutEnabled) {
loginDao.updateFailAttemptsForPubPortal(domainName, name);
}
} else {
loginDao.updateFailAttemptsForPubPortal(domainName,name);
}
}
throw new BadCredentialsException(
"Invalid username/password");
}
}
conn.commit();
}
// }
} catch (Exception e) {
log.error("AuthenticationDAOImpl : " + Constants.LOG_EXCEPTION + e.getMessage());
e.printStackTrace();
try {
conn.rollback();
throw new DataNotFoundException(
"Invalid username/password");
} catch (SQLException e1) {
log.error("AuthenticationDAOImpl : " + Constants.LOG_CREATE_SQLEXCEPTION + e.getMessage());
e1.printStackTrace();
} catch (DataNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
} finally {
if (log.isInfoEnabled()) {
log.info("AuthenticationDAOImpl : " + Constants.LOG_CONNECTION_CLOSE);
}
MySqlDBConnection.closeDbConnection(conn);
}
Authentication resultAuthentication = new UsernamePasswordAuthenticationToken(authentication.getPrincipal(),authentication.getCredentials(),authorities);
if (log.isDebugEnabled()) {
if(resultAuthentication == null){
log.debug("authenticate : Resultset is null");
}else{
log.debug("authenticate :"+resultAuthentication.toString()+" Exit ");
}}
return resultAuthentication;
}
@Override
public boolean supports(Class<?> arg0) {
return true;
}
public static boolean isLDAPUser(String domainName, String consDomainName, String name, Connection conn) {
...
}
}