简体   繁体   English

当有servlet网址时,Spring安全性登录表单不起作用:本地主机:8080 / nameWeb /登录

[英]Spring security login form does not work when there is servlet Url: localhost: 8080 / nameWeb / login

I'm building a spring mvc application and include spring security for logging in and out, but when I add the context of the root 'TechZone' behind: "localhost: 8080 / TechZone / login" it doesn't work , it seems that the default security application only accepts "localhost: 8080 / login". 我正在构建一个Spring MVC应用程序,并包括用于登录和注销的Spring安全性,但是当我在根后面添加“ TechZone”根的上下文时:“ localhost:8080 / TechZone / login”,它不起作用,似乎默认的安全应用程序仅接受“ localhost:8080 / login”。 How to correctly configure the servlet url customization, if anyone knows please help me and I appreciate it! 如何正确配置servlet url定制,如果有人知道,请帮助我,我非常感谢!

package com.techzone.springmvc.config;


import java.util.Properties;

import org.apache.commons.dbcp.BasicDataSource;
import org.hibernate.SessionFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor;
import org.springframework.orm.hibernate5.HibernateTransactionManager;
import org.springframework.orm.hibernate5.LocalSessionFactoryBean;
import org.springframework.orm.jpa.JpaVendorAdapter;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;


@Configuration
@EnableTransactionManagement
public class DatabaseConfig extends WebMvcConfigurerAdapter {

    final static String PACKAGE_SCAN = "com.techzone.springmvc";


    private Properties hibernateProperties() {
        Properties properties = new Properties();
        properties.put("hibernate.dialect", "org.hibernate.dialect.MySQL5Dialect");
        properties.put("hibernate.show_sql", true);
        properties.put("hibernate.format_sql", true);
        properties.put("hibernate.hbm2ddl.auto", "update");
        return properties;
    }

    @Bean(name = "dataSource")
    public BasicDataSource getDataSource() {
        BasicDataSource dataSource = new BasicDataSource();
        dataSource.setDriverClassName("com.mysql.jdbc.Driver");
        dataSource.setUrl("jdbc:mysql://localhost:3306/TechZone?useSSL=false");
        dataSource.setUsername("springstudent");
        dataSource.setPassword("springstudent");
        return dataSource;
    }

    @Bean
    public LocalSessionFactoryBean sessionFactoryBean(BasicDataSource dataSource) {
        LocalSessionFactoryBean sessionFactoryBean = new LocalSessionFactoryBean();
        sessionFactoryBean.setDataSource(dataSource);
        sessionFactoryBean.setPackagesToScan(PACKAGE_SCAN);
        sessionFactoryBean.setHibernateProperties(hibernateProperties());
        return sessionFactoryBean;
    }

//  @Bean /** PersistenceJPAConfig **/
//  public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
//      LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean();
//      factory.setDataSource(getDataSource());
//      factory.setPackagesToScan(PACKAGE_SCAN);
//      JpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
//      factory.setJpaVendorAdapter(vendorAdapter);
//      factory.setJpaProperties(hibernateProperties());
//   
//      return factory;
//     }



//  @Bean
//  public HibernateTransactionManager transactionManager(SessionFactory session) {
//      HibernateTransactionManager manager = new HibernateTransactionManager();
//      manager.setSessionFactory(session);
//      return manager;
//  }
//  
//  @Bean
//  public PersistenceExceptionTranslationPostProcessor exceptionTranslation(){
//      return new PersistenceExceptionTranslationPostProcessor();
//  }



}
public class SecurityWebApplicationInitializer extends AbstractSecurityWebApplicationInitializer {

    // AUTO

}
package com.techzone.springmvc.config;

import javax.annotation.Resource;

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.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;

@Configuration
@EnableWebSecurity
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {

    @Resource(name = "userDetailService")
    private UserDetailsService userDetailsService;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().requireCsrfProtectionMatcher(new AntPathRequestMatcher("**/login"))
        .and().authorizeRequests()
        .antMatchers("**/login").permitAll()
        .antMatchers("/dashboard").hasRole("USER")
        .and().formLogin().defaultSuccessUrl("/dashboard").loginProcessingUrl("/login")
        .loginPage("/login").and().logout().permitAll();
    }


    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers("/*.css");
        web.ignoring().antMatchers("/*.js");
    }

    @Bean
    public PasswordEncoder passwordEncoder(){
        PasswordEncoder encoder = new BCryptPasswordEncoder();
        return encoder;
    }

    @Autowired
    public void configureGlobalSecurity(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
    }



}

package com.techzone.springmvc.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.i18n.LocaleChangeInterceptor;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.springframework.web.servlet.view.JstlView;

@EnableWebMvc
@Configuration
@ComponentScan({"com.techzone.springmvc"})
public class MvcConfig extends WebMvcConfigurerAdapter { // TODO INFO: This's the dispatcher servlet's Spring application context //


    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {

        registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
        registry.addResourceHandler("/*.js/**").addResourceLocations("/views/static/");
        registry.addResourceHandler("/*.css/**").addResourceLocations("/views/static/");

    }

    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/").setViewName("home");
    }

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


    @Bean
    public InternalResourceViewResolver viewResolver() {
        InternalResourceViewResolver resourceView = new InternalResourceViewResolver();
        resourceView.setViewClass(JstlView.class);
        resourceView.setPrefix("/views/jsp/");
        resourceView.setSuffix(".jsp");
        return resourceView;
    }

    // for upload image
    @Bean(name = "multipartResolver")
    public CommonsMultipartResolver multipartResolver() {
        CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver();
        return multipartResolver;
    }

    // multiple Language
    @Override
    public void addInterceptors(InterceptorRegistry interceptorRegistry) {
        LocaleChangeInterceptor localeChangeInterceptor = new LocaleChangeInterceptor();
        localeChangeInterceptor.setParamName("lang");
        interceptorRegistry.addInterceptor(localeChangeInterceptor).addPathPatterns("/*");
    }


}
package com.techzone.springmvc.config;

import javax.servlet.FilterRegistration;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;

import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.ContextLoaderListener;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.filter.CharacterEncodingFilter;
import org.springframework.web.servlet.DispatcherServlet;

public class WebAppInitializer implements WebApplicationInitializer {

    public void onStartup(ServletContext servletContext) throws ServletException {

        // TODO : Create the root spring application context
        AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext();
        rootContext.register(MvcConfig.class, DatabaseConfig.class,MessageResourcesConfig.class,SpringSecurityConfig.class);

        // TODO : Manager life cycle of the root application context
        servletContext.addListener(new ContextLoaderListener(rootContext));

        // TODO : Create the dispatcher servlet's spring application context
        AnnotationConfigWebApplicationContext dispatcherServlet = new AnnotationConfigWebApplicationContext();
        dispatcherServlet.register(MvcConfig.class);

        // TODO : Register and map the dispatcher servlet
        ServletRegistration.Dynamic dispatcher = servletContext.addServlet("dispatcher", new DispatcherServlet(dispatcherServlet));
        dispatcher.setLoadOnStartup(1);
        dispatcher.addMapping("/");

        // TODO : Filter Character UTF-8
        FilterRegistration.Dynamic filter = servletContext.addFilter("encodingFilter", CharacterEncodingFilter.class);
        filter.setInitParameter("encoding", "UTF-8");
        filter.setInitParameter("forceEncoding", "true");
        filter.addMappingForUrlPatterns(null, true, "/*");

    }

}
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix="spring" uri="http://www.springframework.org/tags"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    isELIgnored="false" pageEncoding="UTF-8"%>
<html>
<head>
<title>Spring Security Example</title>
<link href="/bootstrap.min.css" rel="stylesheet">
<script src="/jquery-2.2.1.min.js"></script>
<script src="/bootstrap.min.js"></script>
</head>
<body>
    <div class="container" style="margin: 50px;border: 1px solid green;">
        <h3>Spring Security Login Example</h3>
        <c:if test="${param.error ne null}">
            <div style="color: red">Invalid credentials.</div>
        </c:if>
        <form action="/login" method="post">
            <div class="form-group">
                <label for="username">UserName:</label> <input type="text"
                    class="form-control" id="username" name="username">
            </div>
            <div class="form-group">
                <label for="pwd">Password:</label> <input type="password"
                    class="form-control" id="password" name="password">
            </div>

            <button type="submit" class="btn btn-success">Submit</button>

            <input type="hidden" name="${_csrf.parameterName}"
                value="${_csrf.token}" />
        </form>
    </div>
</body>
</html>

** I expect it work with localhost:8080/nameYourApp/login instead of localhost:8080/login ** Pic1 Pic2 **我希望它与本地主机的工作:8080 / nameYourApp /登录以代替localhost:8080 /登录** PIC1 PIC2

您可以定义完整的安全性登录路径(新的AntPathRequestMatcher(“ / TechZone / login”));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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