简体   繁体   中英

intercept-url spring security cant get it right with custom login

im trying to authenticate a user defined in the code from a html login page this is my configuration.

<security:http auto-config="true">

 <security:intercept-url pattern="/**" access="hasRole('ROLE_Usuario')" />

 <security:form-login
        login-page="/login"
        default-target-url="/inicio"
        authentication-failure-url="/login"
        username-parameter="nombreUsuario"
        password-parameter="contrasena" />
        <security:logout logout-success-url="/login" />         

 </security:http>

 <security:authentication-manager>
 <security:authentication-provider>
 <security:user-service>
 <security:user name="manuel" password="1234" authorities="ROLE_Usuario" />
 </security:user-service>
 </security:authentication-provider>
 </security:authentication-manager>

if i use pattern="/ " i cant get to login jsp and controllers never get a request because a 403 error, if i put pattern=/inicio/ which is the first page after login the application just protect /inicio and no other pages and beside that the login.jsp does not authenticate right.

Could someone please explain how can i protect my pages letting public logic and resources so the pages can get the javascript and css files right and the application do the authentication process.

I want to add something for spring security i configure it with dispatcherServlet instead a ContextLoaderListener could be this the problem? i will try it and test it.

You can add the interceptors for anonymous user access before the interceptors for authenticated users.

In this example /inicio has a permitAll that means that any user has access to it. (put this interceptor at the top)

 <security:intercept-url pattern="/inicio" access="permitAll()" />

Now the /resoruces/** will be accessed for all the users too. (put this interceptor as a second one), assuming that you have a resources folder where are located the .js and .css files.

 <security:intercept-url pattern="/resources/**" access="permitAll()" />

And after that comes the private access, Spring Security will evaluate in the order that you put the interceptors.

 <security:intercept-url pattern="/**" access="hasRole('ROLE_Usuario')" />

Here is a complete working approach, please review if it can help to get your solution:

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.spring.security.demoxml</groupId>
    <artifactId>xml-spring-security-demo</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>war</packaging>
    <properties>
        <spring.version>4.3.10.RELEASE</spring.version>
        <spring.security.version>4.2.3.RELEASE</spring.security.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-web</artifactId>
            <version>${spring.security.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-config</artifactId>
            <version>${spring.security.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-core</artifactId>
            <version>${spring.security.version}</version>
        </dependency>

    </dependencies>


</project>

web.xml , make sure that your springSecurityFilterChain is on your web.xml like this:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
         version="3.1">
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>WEB-INF/spring-servlet.xml</param-value>
    </context-param>
    <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>
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <servlet>
        <servlet-name>spring</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>spring</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
</web-app>

spring-servlet.xml Dispatcher servlet configuration, I use the same dispatcher servlet config to put all the security configuration, of course is not a god practice, it is just an example.

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:security="http://www.springframework.org/schema/security"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security.xsd">
<context:component-scan base-package="com.mydemo.spring" ></context:component-scan>

<security:http auto-config="true">
    <security:intercept-url pattern="/index" access="permitAll()" />
    <security:intercept-url pattern="/**" access="hasRole('ROLE_Usuario')"></security:intercept-url>

    <security:form-login authentication-success-forward-url="/private"
                         default-target-url="/private"
                         username-parameter="username"
                         password-parameter="password"/>
    <security:logout logout-success-url="/login" logout-url="/logout"></security:logout>

</security:http>
    <security:authentication-manager>
        <security:authentication-provider>
            <security:user-service>
                <security:user name="manuel" password="1234" authorities="ROLE_Usuario" />
            </security:user-service>
        </security:authentication-provider>
    </security:authentication-manager>
</beans>

MainController.java the main controller has two RequestMapping /index for public access and /private for private access.

package com.mydemo.spring.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class MainController {

    @RequestMapping(value = "/index")
    public String main(){
        return "index";
    }

    @RequestMapping(value = "/private")
    public String getPrivate(){
        return "private";
    }
}

Application.java (here is the configuration of the Internal Resource View Resolver)

package com.mydemo.spring;


import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.InternalResourceViewResolver;

@Configuration
@EnableWebMvc
public class Application extends WebMvcConfigurerAdapter
{

    @Bean
    public InternalResourceViewResolver getViewResolver(){
        InternalResourceViewResolver c = new InternalResourceViewResolver();
        c.setPrefix("/");
        c.setSuffix(".jsp");
        return c;
    }

    @Override
    public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer){
        configurer.enable();

    }
}

index.jsp (public access)

<html lang="en">
<head>
    <meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
    <title>Document</title>
</head>
<body>
<h1>hi</h1>
</body>
</html>

login.jsp (login page)

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Login</title>
</head>
<body>
<form 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>
</body>
</html>

private.jsp (the private section)

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<h1>Private Page</h1>
</body>
</html>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM