manual authentication demo integration (#836)

* manual authentication demo integration

* apply eclipse and security formatting rules

* add content to readme file, for manual authentication demo
This commit is contained in:
gitterjim-I 2016-11-23 20:57:39 +00:00 committed by Zeger Hendrikse
parent 19b4155ef3
commit 5f9ef96503
11 changed files with 230 additions and 1 deletions

View File

@ -1,2 +1,11 @@
###The Course
=========
## Spring Security Authentication/Authorization Example Project
##The Course
The "REST With Spring" Classes: http://github.learnspringsecurity.com
### Relevant Articles:
- [Spring Security Manual Authentication](http://www.baeldung.com/spring-security-authentication)
### Build the Project
mvn clean install

View File

@ -8,9 +8,11 @@ import org.springframework.web.servlet.config.annotation.EnableWebMvc;
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.context.annotation.Profile;
@Configuration
@EnableWebMvc
@Profile("!manual")
public class MvcConfig extends WebMvcConfigurerAdapter {
public MvcConfig() {

View File

@ -0,0 +1,22 @@
package org.baeldung.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
@Configuration
@EnableWebMvc
@Profile("manual")
public class MvcConfigManual extends WebMvcConfigurerAdapter {
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/home").setViewName("home");
registry.addViewController("/").setViewName("home");
registry.addViewController("/hello").setViewName("hello");
registry.addViewController("/login").setViewName("login");
}
}

View File

@ -0,0 +1,92 @@
package org.baeldung.config;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AbstractAuthenticationToken;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetails;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.context.annotation.Profile;
/**
* Manually authenticate a user using Spring Security / Spring Web MVC' (upon successful account registration)
* (http://stackoverflow.com/questions/4664893/how-to-manually-set-an-authenticated-user-in-spring-security-springmvc)
*
* @author jim clayson
*/
@Controller
@Profile("manual")
public class RegistrationController {
private static final Logger logger = LoggerFactory.getLogger(RegistrationController.class);
@Autowired
AuthenticationManager authenticationManager;
/**
* For demo purposes this need only be a GET request method
*
* @param request
* @param response
* @return The view. Page confirming either successful registration (and/or
* successful authentication) or failed registration.
*/
@RequestMapping(value = "/register", method = RequestMethod.GET)
public String registerAndAuthenticate(HttpServletRequest request, HttpServletResponse response) {
logger.debug("registerAndAuthenticate: attempt to register, application should manually authenticate.");
// Mocked values. Potentially could come from an HTML registration form,
// in which case this mapping would match on an HTTP POST, rather than a GET
String username = "user";
String password = "password";
String view = "registrationSuccess";
if (requestQualifiesForManualAuthentication()) {
try {
authenticate(username, password, request, response);
logger.debug("registerAndAuthenticate: authentication completed.");
} catch (BadCredentialsException bce) {
logger.debug("Authentication failure: bad credentials");
bce.printStackTrace();
view = "systemError"; // assume a low-level error, since the registration
// form would have been successfully validated
}
}
return view;
}
private boolean requestQualifiesForManualAuthentication() {
// Some processing to determine that the user requires a Spring Security-recognized,
// application-directed login e.g. successful account registration.
return true;
}
private void authenticate(String username, String password, HttpServletRequest request, HttpServletResponse response) throws BadCredentialsException {
logger.debug("attempting to authenticated, manually ... ");
// create and populate the token
AbstractAuthenticationToken authToken = new UsernamePasswordAuthenticationToken(username, password);
authToken.setDetails(new WebAuthenticationDetails(request));
// This call returns an authentication object, which holds principle and user credentials
Authentication authentication = this.authenticationManager.authenticate(authToken);
// The security context holds the authentication object, and is stored
// in thread local scope.
SecurityContextHolder.getContext().setAuthentication(authentication);
logger.debug("User should now be authenticated.");
}
}

View File

@ -6,9 +6,11 @@ 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.context.annotation.Profile;
@Configuration
@EnableWebSecurity
@Profile("!manual")
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override

View File

@ -0,0 +1,35 @@
package org.baeldung.config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
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
@Profile("manual")
public class WebSecurityConfigManual extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
// @formatter:off
http
.authorizeRequests()
.antMatchers("/", "/home", "/register").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login").permitAll()
.and()
.logout().permitAll();
// @formatter:on
}
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication().withUser("user").password("password").roles("USER");
}
}

View File

@ -0,0 +1,15 @@
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org"
xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity3">
<head>
<title>Hello World!</title>
</head>
<body>
<h1 th:inline="text">Hello [[${#httpServletRequest.remoteUser}]]!</h1>
<form th:action="@{/logout}" method="post">
<input type="submit" value="Sign Out"/>
</form>
<p>Click <a th:href="@{/home}">here</a> to go to the home page.</p>
</body>
</html>

View File

@ -0,0 +1,15 @@
<!DOCTYPE html>
<html
xmlns="http://www.w3.org/1999/xhtml"
xmlns:th="http://www.thymeleaf.org"
xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity4">
<head>
<title>Spring Security Example</title>
</head>
<body>
<h1>Welcome!</h1>
<p>Click <a th:href="@{/hello}">here</a> to see a greeting.</p>
<p sec:authorize="isAnonymous()">Click <a th:href="@{/register}">here</a> to send a dummy registration request, where the application logs you in.</p>
</body>
</html>

View File

@ -0,0 +1,21 @@
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org"
xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity3">
<head>
<title>Spring Security Example </title>
</head>
<body>
<div th:if="${param.error}">
Invalid username and password.
</div>
<div th:if="${param.logout}">
You have been logged out.
</div>
<form th: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>
<p>Click <a th:href="@{/home}">here</a> to go to the home page.</p>
</body>
</html>

View File

@ -0,0 +1 @@
Registration could not be completed at this time. Please try again later or contact support!

View File

@ -0,0 +1,15 @@
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org"
xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity3">
<head>
<title>Registration Success!</title>
</head>
<body>
<h2 th:inline="text">Registration succeeded. You have been logged in by the system. Welcome [[${#httpServletRequest.remoteUser}]]!</h2>
<form th:action="@{/logout}" method="post">
<input type="submit" value="Sign Out"/>
</form>
<p>Click <a th:href="@{/home}">here</a> to go to the home page.</p>
</body>
</html>