自定义登录 jsp + spring boot 安全功能

huangapple 未分类评论51阅读模式
英文:

Custom Login jsp + spring boot security

问题

这是 JSP 部分:

<!-- 登录表单 -->
<form action="${pageContext.request.contextPath}/authenticateTheUser" method="POST" class="form-horizontal">

    <!-- 消息显示区域:错误、警告等 -->
    <div class="form-group">
        <div class="col-xs-15">
            <div>
                <!-- 检查登录错误 -->
                <c:if test="${param.error != null}">
                    <div class="alert alert-danger col-xs-offset-1 col-xs-10">
                        无效的用户名和密码。
                    </div>
                </c:if>

                <!-- 检查登出 -->
                <c:if test="${param.logout != null}">
                    <div class="alert alert-success col-xs-offset-1 col-xs-10">
                        您已登出。
                    </div>
                </c:if>
            </div>
        </div>
    </div>

    <!-- 用户名 -->
    <div style="margin-bottom: 25px" class="input-group">
        <span class="input-group-addon"><i class="glyphicon glyphicon-user"></i></span>
        <input type="text" name="username" placeholder="用户名" class="form-control">
    </div>

    <!-- 密码 -->
    <div style="margin-bottom: 25px" class="input-group">
        <span class="input-group-addon"><i class="glyphicon glyphicon-lock"></i></span>
        <input type="password" name="password" placeholder="密码" class="form-control">
    </div>

    <!-- 登录/提交按钮 -->
    <div style="margin-top: 10px" class="form-group">
        <div class="col-sm-6 controls">
            <button type="submit" class="btn btn-success">登录</button>
        </div>
    </div>

    <!-- 手动添加令牌 -->
    <input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}" />

</form>

配置部分:

package com.crm.config;

import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
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 DemoSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    @Qualifier("securityDataSource")
    private DataSource securityDataSource;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.jdbcAuthentication().dataSource(securityDataSource);
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
            .antMatchers("/employees/showForm*").hasAnyRole("MANAGER", "ADMIN")
            .antMatchers("/employees/save*").hasAnyRole("MANAGER", "ADMIN")
            .antMatchers("/employees/delete").hasRole("ADMIN")
            .antMatchers("/employees/**").hasRole("EMPLOYEE")
            .antMatchers("/resources/**").permitAll()
            .antMatchers("/showMyLoginPage").permitAll()
            .and()
            .formLogin()
                .loginPage("/showMyLoginPage")
                .loginProcessingUrl("/authenticateTheUser")
                .permitAll()
            .and()
            .logout().permitAll()
            .and()
            .exceptionHandling().accessDeniedPage("/access-denied");
    }
}

控制器部分:

@GetMapping("/showMyLoginPage")
public String showMyLoginPage() {
    return "fancy-login";
}

@GetMapping("/access-denied")
public String showAccessDenied() {
    return "access-denied";
}

如果你还有其他问题,请随时问我。

英文:

I'm just learning all about spring and I was triying to do my own project but instead of use thymeleaf I'll use JSP. I have an example running with spring boot + spring security and it own custom login. I do the same, but instead of html+thymeleaf, I'm using jsp but the custom login is not showing, always appear the default spring security login, any help?

This is the JSP:

&lt;!-- Login Form --&gt;
				&lt;form action=&quot;${pageContext.request.contextPath}/authenticateTheUser&quot; 
					  method=&quot;POST&quot; class=&quot;form-horizontal&quot;&gt;

				    &lt;!-- Place for messages: error, alert etc ... --&gt;
				    &lt;div class=&quot;form-group&quot;&gt;
				        &lt;div class=&quot;col-xs-15&quot;&gt;
				            &lt;div&gt;
							
								&lt;!-- Check for login error --&gt;
							
								&lt;c:if test=&quot;${param.error != null}&quot;&gt;
									
									&lt;div class=&quot;alert alert-danger col-xs-offset-1 col-xs-10&quot;&gt;
										Invalid username and password.
									&lt;/div&gt;
	
								&lt;/c:if&gt;
									
								&lt;!-- Check for logout --&gt;

								&lt;c:if test=&quot;${param.logout != null}&quot;&gt;
									            
									&lt;div class=&quot;alert alert-success col-xs-offset-1 col-xs-10&quot;&gt;
										You have been logged out.
									&lt;/div&gt;
							    
								&lt;/c:if&gt;
								
				            &lt;/div&gt;
				        &lt;/div&gt;
				    &lt;/div&gt;

					&lt;!-- User name --&gt;
					&lt;div style=&quot;margin-bottom: 25px&quot; class=&quot;input-group&quot;&gt;
						&lt;span class=&quot;input-group-addon&quot;&gt;&lt;i class=&quot;glyphicon glyphicon-user&quot;&gt;&lt;/i&gt;&lt;/span&gt; 
						
						&lt;input type=&quot;text&quot; name=&quot;username&quot; placeholder=&quot;username&quot; class=&quot;form-control&quot;&gt;
					&lt;/div&gt;

					&lt;!-- Password --&gt;
					&lt;div style=&quot;margin-bottom: 25px&quot; class=&quot;input-group&quot;&gt;
						&lt;span class=&quot;input-group-addon&quot;&gt;&lt;i class=&quot;glyphicon glyphicon-lock&quot;&gt;&lt;/i&gt;&lt;/span&gt; 
						
						&lt;input type=&quot;password&quot; name=&quot;password&quot; placeholder=&quot;password&quot; class=&quot;form-control&quot; &gt;
					&lt;/div&gt;

					&lt;!-- Login/Submit Button --&gt;
					&lt;div style=&quot;margin-top: 10px&quot; class=&quot;form-group&quot;&gt;						
						&lt;div class=&quot;col-sm-6 controls&quot;&gt;
							&lt;button type=&quot;submit&quot; class=&quot;btn btn-success&quot;&gt;Login&lt;/button&gt;
						&lt;/div&gt;
					&lt;/div&gt;

					&lt;!-- I&#39;m manually adding tokens ... Bro! --&gt;

					&lt;input type=&quot;hidden&quot;
						   name=&quot;${_csrf.parameterName}&quot;
						   value=&quot;${_csrf.token}&quot; /&gt;
					
				&lt;/form&gt;

The configuration:

package com.crm.config;

import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
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 DemoSecurityConfig extends WebSecurityConfigurerAdapter {

	// add a reference to our security data source
	
	@Autowired
	@Qualifier(&quot;securityDataSource&quot;)
	private DataSource securityDataSource;
	
	
	@Override
	protected void configure(AuthenticationManagerBuilder auth) throws Exception {

		auth.jdbcAuthentication().dataSource(securityDataSource);
		
	}

	@Override
	protected void configure(HttpSecurity http) throws Exception {

		System.out.println(&quot;aplicando configuracion&quot;);
		http.authorizeRequests()
		.antMatchers(&quot;/employees/showForm*&quot;).hasAnyRole(&quot;MANAGER&quot;, &quot;ADMIN&quot;)
		.antMatchers(&quot;/employees/save*&quot;).hasAnyRole(&quot;MANAGER&quot;, &quot;ADMIN&quot;)
		.antMatchers(&quot;/employees/delete&quot;).hasRole(&quot;ADMIN&quot;)
		.antMatchers(&quot;/employees/**&quot;).hasRole(&quot;EMPLOYEE&quot;)
		.antMatchers(&quot;/resources/**&quot;).permitAll()
		.antMatchers(&quot;/showMyLoginPage&quot;).permitAll()
		.and()
		.formLogin()
			.loginPage(&quot;/showMyLoginPage&quot;)
			.loginProcessingUrl(&quot;/authenticateTheUser&quot;)
			.permitAll()
		.and()
		.logout().permitAll()
		.and()
		.exceptionHandling().accessDeniedPage(&quot;/access-denied&quot;);
		
	}
		


}

And the controller:

	@GetMapping(&quot;/showMyLoginPage&quot;)
public String showMyLoginPage() {
	
	return &quot;fancy-login&quot;;
	
}

// add request mapping for /access-denied

@GetMapping(&quot;/access-denied&quot;)
public String showAccessDenied() {
	
	return &quot;access-denied&quot;;
	
}

Here you have the link in github
https://github.com/a343/srping

Many thanks in advance.

Regards

huangapple
  • 本文由 发表于 2020年5月4日 00:09:12
  • 转载请务必保留本文链接:https://java.coder-hub.com/61577659.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定