fix requested comments

This commit is contained in:
nnhai1991@gmail.com 2018-08-18 17:23:07 +08:00
parent 4b1f955980
commit 0d684eed97
5 changed files with 62 additions and 46 deletions

View File

@ -1,40 +1,41 @@
package org.baeldung.security; package org.baeldung.security;
import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer; import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration; 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.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.factory.PasswordEncoderFactories; import org.springframework.security.core.userdetails.User;
import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
@SpringBootApplication @SpringBootApplication
@Configuration @Configuration
@EnableWebSecurity @EnableWebSecurity
public class ApplicationConfig extends WebSecurityConfigurerAdapter { public class ApplicationConfig extends WebSecurityConfigurerAdapter {
public static final String DEFAULT_PASSWORD = "password";
// Using withDefaultPasswordEncoder and InMemoryUserDetailsManager for demonstration and testing purpose
@Bean
@Override @Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception { public UserDetailsService userDetailsService() {
PasswordEncoder encoder = PasswordEncoderFactories.createDelegatingPasswordEncoder(); UserDetails user = User.withDefaultPasswordEncoder()
.username("testUser")
.password("password")
.roles("ADMIN")
.build();
auth.inMemoryAuthentication() return new InMemoryUserDetailsManager(user);
.passwordEncoder(encoder)
.withUser("testUser")
.password(encoder.encode(DEFAULT_PASSWORD))
.roles("ADMIN");
} }
@Override @Override
protected void configure(HttpSecurity http) throws Exception { protected void configure(HttpSecurity http) throws Exception {
http.csrf(); // @formatter:off
http.csrf()
http.authorizeRequests() .and()
.antMatchers("/**") .authorizeRequests()
.permitAll() .anyRequest().permitAll().and().httpBasic();
.and() // @formatter:on
.httpBasic();
} }
} }

View File

@ -1,6 +1,7 @@
package org.baeldung.security; package org.baeldung.security;
import org.springframework.stereotype.Controller; import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMapping;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequest;
@ -9,8 +10,9 @@ import javax.servlet.http.HttpServletResponse;
@Controller @Controller
@RequestMapping("/") @RequestMapping("/")
public class HomeController { public class HomeController {
@RequestMapping("")
public String home(HttpServletRequest request, HttpServletResponse response) { @GetMapping
public String home() {
return "home"; return "home";
} }
} }

View File

@ -1,8 +1,3 @@
#jsp config #jsp config
spring.mvc.view.prefix: /WEB-INF/views/ spring.mvc.view.prefix: /WEB-INF/views/
spring.mvc.view.suffix: .jsp spring.mvc.view.suffix: .jsp
spring.http.encoding.charset=UTF-8
# Enable http encoding support.
spring.http.encoding.enabled=true
# Force the encoding to the configured charset on HTTP requests and responses.
spring.http.encoding.force=true

View File

@ -1,5 +1,7 @@
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <%@ page language="java" contentType="text/html; charset=UTF-8"
<%@ taglib prefix="sec" uri="http://www.springframework.org/security/tags"%> pageEncoding="UTF-8"%>
<%@ taglib prefix="sec"
uri="http://www.springframework.org/security/tags"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html> <html>
<head> <head>
@ -8,21 +10,22 @@
<title>Home Page</title> <title>Home Page</title>
</head> </head>
<body> <body>
<sec:authorize access="isAnonymous()">
ANONYMOUS
</sec:authorize>
<sec:authorize access="isAuthenticated()"> <sec:authorize access="isAuthenticated()">
AUTHENTICATED AUTHENTICATED
<sec:authorize access="hasRole('ADMIN')">
ADMIN ROLE
</sec:authorize>
<h2>
principal.username:
<sec:authentication property="principal.username" />
</h2>
<form>
<sec:csrfInput />
Text Field: <br /> <input type="text" name="textField" />
</form>
</sec:authorize> </sec:authorize>
<sec:authorize access="hasRole('ADMIN')">
ADMIN ROLE
</sec:authorize>
<h2>
principal.username:
<sec:authentication property="principal.username" />
</h2>
<form method="post" action="/do/something">
<sec:csrfInput />
Text Field:
<br />
<input type="text" name="textField" />
</form>
</body> </body>
</html> </html>

View File

@ -1,5 +1,6 @@
package org.baeldung.security; package org.baeldung.security;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertTrue;
import org.junit.Test; import org.junit.Test;
@ -18,11 +19,13 @@ public class HomeControllerTest {
private TestRestTemplate restTemplate; private TestRestTemplate restTemplate;
@Test @Test
public void home() throws Exception { public void whenUserIsAuthenticatedThenAuthenticatedSectionsShowOnSite() throws Exception {
String body = this.restTemplate.withBasicAuth("testUser", ApplicationConfig.DEFAULT_PASSWORD) String body = this.restTemplate.withBasicAuth("testUser", "password")
.getForEntity("/", String.class) .getForEntity("/", String.class)
.getBody(); .getBody();
System.out.println(body);
// test <sec:authorize access="isAnonymous()">
assertFalse(body.contains("ANONYMOUS"));
// test <sec:authorize access="isAuthenticated()"> // test <sec:authorize access="isAuthenticated()">
assertTrue(body.contains("AUTHENTICATED")); assertTrue(body.contains("AUTHENTICATED"));
@ -31,7 +34,7 @@ public class HomeControllerTest {
assertTrue(body.contains("ADMIN ROLE")); assertTrue(body.contains("ADMIN ROLE"));
// test <sec:authentication property="principal.username" /> // test <sec:authentication property="principal.username" />
assertTrue(body.contains("principal.username: testUser")); assertTrue(body.contains("testUser"));
// test <sec:csrfInput /> // test <sec:csrfInput />
assertTrue(body.contains("<input type=\"hidden\" name=\"_csrf\" value=\"")); assertTrue(body.contains("<input type=\"hidden\" name=\"_csrf\" value=\""));
@ -39,4 +42,16 @@ public class HomeControllerTest {
// test <sec:csrfMetaTags /> // test <sec:csrfMetaTags />
assertTrue(body.contains("<meta name=\"_csrf_parameter\" content=\"_csrf\" />")); assertTrue(body.contains("<meta name=\"_csrf_parameter\" content=\"_csrf\" />"));
} }
@Test
public void whenUserIsNotAuthenticatedThenOnlyAnonymousSectionsShowOnSite() throws Exception {
String body = this.restTemplate.getForEntity("/", String.class)
.getBody();
// test <sec:authorize access="isAnonymous()">
assertTrue(body.contains("ANONYMOUS"));
// test <sec:authorize access="isAuthenticated()">
assertFalse(body.contains("AUTHENTICATED"));
}
} }