add oauth2 google
This commit is contained in:
parent
71448364d7
commit
ac55481bc6
@ -105,6 +105,9 @@ dependencies {
|
||||
compile group: 'org.thymeleaf.extras', name: 'thymeleaf-extras-springsecurity5'
|
||||
compile group: 'com.fasterxml.jackson.module', name: 'jackson-module-afterburner'
|
||||
compile group: 'com.fasterxml.jackson.datatype', name: 'jackson-datatype-hibernate5'
|
||||
compile group: 'org.springframework.security', name: 'spring-security-oauth2-client'
|
||||
compile group: 'org.springframework.security', name: 'spring-security-oauth2-jose'
|
||||
compile group: 'org.springframework.security.oauth.boot', name: 'spring-security-oauth2-autoconfigure'
|
||||
|
||||
compile group: 'org.postgresql', name: 'postgresql', version: '42.2.5'
|
||||
|
||||
|
@ -9,7 +9,5 @@ public class MvcConfiguration implements WebMvcConfigurer {
|
||||
@Override
|
||||
public void addViewControllers(ViewControllerRegistry registry) {
|
||||
registry.addRedirectViewController("/", "/index.xhtml");
|
||||
registry.addRedirectViewController("/default", "/index.xhtml");
|
||||
|
||||
}
|
||||
}
|
||||
|
@ -5,27 +5,48 @@ import org.slf4j.LoggerFactory;
|
||||
import org.springframework.beans.factory.BeanInitializationException;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.core.env.Environment;
|
||||
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
|
||||
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
|
||||
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.config.oauth2.client.CommonOAuth2Provider;
|
||||
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
|
||||
import org.springframework.security.oauth2.client.endpoint.DefaultAuthorizationCodeTokenResponseClient;
|
||||
import org.springframework.security.oauth2.client.endpoint.OAuth2AccessTokenResponseClient;
|
||||
import org.springframework.security.oauth2.client.endpoint.OAuth2AuthorizationCodeGrantRequest;
|
||||
import org.springframework.security.oauth2.client.registration.ClientRegistration;
|
||||
import org.springframework.security.oauth2.client.registration.ClientRegistrationRepository;
|
||||
import org.springframework.security.oauth2.client.registration.InMemoryClientRegistrationRepository;
|
||||
import org.springframework.security.oauth2.client.web.AuthorizationRequestRepository;
|
||||
import org.springframework.security.oauth2.client.web.HttpSessionOAuth2AuthorizationRequestRepository;
|
||||
import org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest;
|
||||
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
|
||||
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
|
||||
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
|
||||
import ru.ulstu.core.model.AuthFailureHandler;
|
||||
import ru.ulstu.user.controller.UserController;
|
||||
import ru.ulstu.user.model.UserRoleConstants;
|
||||
import ru.ulstu.user.service.UserService;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
@Configuration
|
||||
@EnableWebSecurity
|
||||
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)
|
||||
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
|
||||
private final Logger log = LoggerFactory.getLogger(SecurityConfiguration.class);
|
||||
private static List<String> clients = Arrays.asList("google");
|
||||
private static String CLIENT_PROPERTY_KEY
|
||||
= "spring.security.oauth2.client.registration.";
|
||||
|
||||
@Autowired
|
||||
private Environment env;
|
||||
|
||||
@Value("${server.http.port}")
|
||||
private int httpPort;
|
||||
@ -54,6 +75,124 @@ public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void configure(HttpSecurity http) throws Exception {
|
||||
http.csrf()
|
||||
.disable();
|
||||
if (applicationProperties.isDevMode()) {
|
||||
log.debug("Security disabled");
|
||||
http.authorizeRequests()
|
||||
.anyRequest()
|
||||
.permitAll();
|
||||
http.anonymous()
|
||||
.principal("admin")
|
||||
.authorities(UserRoleConstants.ADMIN);
|
||||
} else {
|
||||
http.authorizeRequests()
|
||||
.antMatchers("/login.xhtml", "/logout")
|
||||
.permitAll()
|
||||
.anyRequest()
|
||||
.authenticated()
|
||||
.and()
|
||||
.formLogin()
|
||||
.loginPage("/login.xhtml")
|
||||
.successHandler(authenticationSuccessHandler)
|
||||
.failureHandler(authenticationFailureHandler)
|
||||
.permitAll()
|
||||
.and()
|
||||
.oauth2Login()
|
||||
.loginPage("/login.xhtml")
|
||||
.authorizationEndpoint()
|
||||
.baseUri("/oauth2/authorize-client")
|
||||
.authorizationRequestRepository(authorizationRequestRepository())
|
||||
.and()
|
||||
.tokenEndpoint()
|
||||
.accessTokenResponseClient(accessTokenResponseClient())
|
||||
.and()
|
||||
.defaultSuccessUrl("/index.xhtml")
|
||||
.failureUrl("/loginFailure")
|
||||
.and()
|
||||
.logout()
|
||||
.logoutSuccessHandler(logoutSuccessHandler)
|
||||
.logoutSuccessUrl(Constants.LOGOUT_URL)
|
||||
.invalidateHttpSession(true)
|
||||
.clearAuthentication(true)
|
||||
.deleteCookies(Constants.COOKIES_NAME)
|
||||
.permitAll();
|
||||
http.csrf().disable();
|
||||
}
|
||||
if (applicationProperties.isUseHttps()) {
|
||||
http.portMapper()
|
||||
.http(httpPort)
|
||||
.mapsTo(httpsPort)
|
||||
.and()
|
||||
.requiresChannel()
|
||||
.anyRequest()
|
||||
.requiresSecure();
|
||||
}
|
||||
}
|
||||
|
||||
@Bean
|
||||
public AuthorizationRequestRepository<OAuth2AuthorizationRequest> authorizationRequestRepository() {
|
||||
return new HttpSessionOAuth2AuthorizationRequestRepository();
|
||||
}
|
||||
|
||||
@Bean
|
||||
public OAuth2AccessTokenResponseClient<OAuth2AuthorizationCodeGrantRequest> accessTokenResponseClient() {
|
||||
DefaultAuthorizationCodeTokenResponseClient accessTokenResponseClient = new DefaultAuthorizationCodeTokenResponseClient();
|
||||
return accessTokenResponseClient;
|
||||
}
|
||||
|
||||
//@Bean
|
||||
public ClientRegistrationRepository clientRegistrationRepository() {
|
||||
List<ClientRegistration> registrations = clients.stream()
|
||||
.map(c -> getRegistration(c))
|
||||
.filter(registration -> registration != null)
|
||||
.collect(Collectors.toList());
|
||||
|
||||
return new InMemoryClientRegistrationRepository(registrations);
|
||||
}
|
||||
|
||||
private ClientRegistration getRegistration(String client) {
|
||||
String clientId = env.getProperty(CLIENT_PROPERTY_KEY + client + ".client-id");
|
||||
|
||||
if (clientId == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
String clientSecret = env.getProperty(CLIENT_PROPERTY_KEY + client + ".client-secret");
|
||||
if (client.equals("google")) {
|
||||
return CommonOAuth2Provider.GOOGLE.getBuilder(client)
|
||||
.clientId(clientId)
|
||||
.clientSecret(clientSecret)
|
||||
.build();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void configure(WebSecurity web) {
|
||||
web.ignoring()
|
||||
.antMatchers("/css/**")
|
||||
.antMatchers("/javax.faces.resource/**")
|
||||
.antMatchers("/js/**")
|
||||
.antMatchers("/templates/**")
|
||||
.antMatchers("/webjars/**")
|
||||
.antMatchers("/img/**");
|
||||
}
|
||||
|
||||
@Autowired
|
||||
public void configureGlobal(AuthenticationManagerBuilder auth) {
|
||||
if (applicationProperties.isDevMode()) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
auth.userDetailsService(userService).passwordEncoder(bCryptPasswordEncoder);
|
||||
} catch (Exception e) {
|
||||
throw new BeanInitializationException("Security configuration failed", e);
|
||||
}
|
||||
}
|
||||
|
||||
/* @Override
|
||||
protected void configure(HttpSecurity http) throws Exception {
|
||||
http.csrf()
|
||||
.disable();
|
||||
@ -126,5 +265,5 @@ public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
|
||||
} catch (Exception e) {
|
||||
throw new BeanInitializationException("Security configuration failed", e);
|
||||
}
|
||||
}
|
||||
}*/
|
||||
}
|
||||
|
@ -1,120 +0,0 @@
|
||||
package ru.ulstu.core.controller;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.validation.FieldError;
|
||||
import org.springframework.web.bind.MethodArgumentNotValidException;
|
||||
import org.springframework.web.bind.annotation.ControllerAdvice;
|
||||
import org.springframework.web.bind.annotation.ExceptionHandler;
|
||||
import org.springframework.web.bind.annotation.ModelAttribute;
|
||||
import ru.ulstu.core.error.EntityIdIsNullException;
|
||||
import ru.ulstu.core.model.ErrorConstants;
|
||||
import ru.ulstu.core.model.response.Response;
|
||||
import ru.ulstu.core.model.response.ResponseExtended;
|
||||
import ru.ulstu.user.error.UserActivationError;
|
||||
import ru.ulstu.user.error.UserEmailExistsException;
|
||||
import ru.ulstu.user.error.UserIdExistsException;
|
||||
import ru.ulstu.user.error.UserIsUndeadException;
|
||||
import ru.ulstu.user.error.UserLoginExistsException;
|
||||
import ru.ulstu.user.error.UserNotActivatedException;
|
||||
import ru.ulstu.user.error.UserPasswordsNotValidOrNotMatchException;
|
||||
import ru.ulstu.user.error.UserResetKeyError;
|
||||
import ru.ulstu.user.error.UserSendingMailException;
|
||||
import ru.ulstu.user.service.UserService;
|
||||
|
||||
import java.util.Set;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
@ControllerAdvice
|
||||
public class AdviceController {
|
||||
private final Logger log = LoggerFactory.getLogger(AdviceController.class);
|
||||
private final UserService userService;
|
||||
|
||||
public AdviceController(UserService userService) {
|
||||
this.userService = userService;
|
||||
}
|
||||
|
||||
@ModelAttribute("currentUser")
|
||||
public String getCurrentUser() {
|
||||
return userService.getCurrentUser().getUserAbbreviate();
|
||||
}
|
||||
|
||||
@ModelAttribute("flashMessage")
|
||||
public String getFlashMessage() {
|
||||
return null;
|
||||
}
|
||||
|
||||
private Response<Void> handleException(ErrorConstants error) {
|
||||
log.warn(error.toString());
|
||||
return new Response<>(error);
|
||||
}
|
||||
|
||||
private <E> ResponseExtended<E> handleException(ErrorConstants error, E errorData) {
|
||||
log.warn(error.toString());
|
||||
return new ResponseExtended<>(error, errorData);
|
||||
}
|
||||
|
||||
@ExceptionHandler(EntityIdIsNullException.class)
|
||||
public Response<Void> handleEntityIdIsNullException(Throwable e) {
|
||||
return handleException(ErrorConstants.ID_IS_NULL);
|
||||
}
|
||||
|
||||
@ExceptionHandler(MethodArgumentNotValidException.class)
|
||||
public ResponseExtended<Set<String>> handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
|
||||
final Set<String> errors = e.getBindingResult().getAllErrors().stream()
|
||||
.filter(error -> error instanceof FieldError)
|
||||
.map(error -> ((FieldError) error).getField())
|
||||
.collect(Collectors.toSet());
|
||||
return handleException(ErrorConstants.VALIDATION_ERROR, errors);
|
||||
}
|
||||
|
||||
@ExceptionHandler(UserIdExistsException.class)
|
||||
public Response<Void> handleUserIdExistsException(Throwable e) {
|
||||
return handleException(ErrorConstants.USER_ID_EXISTS);
|
||||
}
|
||||
|
||||
@ExceptionHandler(UserActivationError.class)
|
||||
public ResponseExtended<String> handleUserActivationError(Throwable e) {
|
||||
return handleException(ErrorConstants.USER_ACTIVATION_ERROR, e.getMessage());
|
||||
}
|
||||
|
||||
@ExceptionHandler(UserLoginExistsException.class)
|
||||
public ResponseExtended<String> handleUserLoginExistsException(Throwable e) {
|
||||
return handleException(ErrorConstants.USER_LOGIN_EXISTS, e.getMessage());
|
||||
}
|
||||
|
||||
@ExceptionHandler(UserEmailExistsException.class)
|
||||
public ResponseExtended<String> handleUserEmailExistsException(Throwable e) {
|
||||
return handleException(ErrorConstants.USER_EMAIL_EXISTS, e.getMessage());
|
||||
}
|
||||
|
||||
@ExceptionHandler(UserPasswordsNotValidOrNotMatchException.class)
|
||||
public Response<Void> handleUserPasswordsNotValidOrNotMatchException(Throwable e) {
|
||||
return handleException(ErrorConstants.USER_PASSWORDS_NOT_VALID_OR_NOT_MATCH);
|
||||
}
|
||||
|
||||
// @ExceptionHandler(UserNotFoundException.class)
|
||||
// public ResponseExtended<String> handleUserNotFoundException(Throwable e) {
|
||||
// return handleException(ErrorConstants.USER_NOT_FOUND, e.getMessage());
|
||||
// }
|
||||
|
||||
@ExceptionHandler(UserNotActivatedException.class)
|
||||
public Response<Void> handleUserNotActivatedException(Throwable e) {
|
||||
return handleException(ErrorConstants.USER_NOT_ACTIVATED);
|
||||
}
|
||||
|
||||
@ExceptionHandler(UserResetKeyError.class)
|
||||
public ResponseExtended<String> handleUserResetKeyError(Throwable e) {
|
||||
return handleException(ErrorConstants.USER_RESET_ERROR, e.getMessage());
|
||||
}
|
||||
|
||||
@ExceptionHandler(UserIsUndeadException.class)
|
||||
public ResponseExtended<String> handleUserIsUndeadException(Throwable e) {
|
||||
return handleException(ErrorConstants.USER_UNDEAD_ERROR, e.getMessage());
|
||||
}
|
||||
|
||||
@ExceptionHandler(UserSendingMailException.class)
|
||||
public ResponseExtended<String> handleUserSendingMailException(Throwable e) {
|
||||
return handleException(ErrorConstants.USER_SENDING_MAIL_EXCEPTION, e.getMessage());
|
||||
}
|
||||
}
|
@ -1,23 +0,0 @@
|
||||
package ru.ulstu.index.controller;
|
||||
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.ui.ModelMap;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import ru.ulstu.core.controller.AdviceController;
|
||||
import ru.ulstu.user.service.UserService;
|
||||
import springfox.documentation.annotations.ApiIgnore;
|
||||
|
||||
@Controller()
|
||||
@RequestMapping(value = "/index")
|
||||
@ApiIgnore
|
||||
public class IndexController extends AdviceController {
|
||||
public IndexController(UserService userService) {
|
||||
super(userService);
|
||||
}
|
||||
|
||||
@GetMapping
|
||||
public void currentUser(ModelMap modelMap) {
|
||||
//нужен здесь для добавления параметров на стартовой странице
|
||||
}
|
||||
}
|
@ -341,10 +341,13 @@ public class UserService implements UserDetailsService {
|
||||
}
|
||||
|
||||
public User getCurrentUser() {
|
||||
String login = UserUtils.getCurrentUserLogin(SecurityContextHolder.getContext());
|
||||
User user = userRepository.findOneByLoginIgnoreCase(login);
|
||||
String loginOrEmail = UserUtils.getCurrentUserLoginOrEmail(SecurityContextHolder.getContext());
|
||||
User user = userRepository.findOneByLoginIgnoreCase(loginOrEmail);
|
||||
if (user == null) {
|
||||
throw new UserNotFoundException(login);
|
||||
user = userRepository.findOneByEmailIgnoreCase(loginOrEmail);
|
||||
}
|
||||
if (user == null) {
|
||||
throw new UserNotFoundException(loginOrEmail);
|
||||
}
|
||||
return user;
|
||||
}
|
||||
|
@ -4,6 +4,7 @@ import org.apache.commons.lang3.RandomStringUtils;
|
||||
import org.springframework.security.core.Authentication;
|
||||
import org.springframework.security.core.context.SecurityContext;
|
||||
import org.springframework.security.core.userdetails.UserDetails;
|
||||
import org.springframework.security.oauth2.core.oidc.user.DefaultOidcUser;
|
||||
import ru.ulstu.configuration.Constants;
|
||||
|
||||
public class UserUtils {
|
||||
@ -17,7 +18,7 @@ public class UserUtils {
|
||||
return RandomStringUtils.randomNumeric(DEF_COUNT);
|
||||
}
|
||||
|
||||
public static String getCurrentUserLogin(SecurityContext securityContext) {
|
||||
public static String getCurrentUserLoginOrEmail(SecurityContext securityContext) {
|
||||
if (securityContext == null) {
|
||||
return null;
|
||||
}
|
||||
@ -27,6 +28,10 @@ public class UserUtils {
|
||||
final UserDetails springSecurityUser = (UserDetails) authentication.getPrincipal();
|
||||
return springSecurityUser.getUsername();
|
||||
}
|
||||
if (authentication.getPrincipal() instanceof DefaultOidcUser) {
|
||||
final DefaultOidcUser oauth2User = (DefaultOidcUser) authentication.getPrincipal();
|
||||
return oauth2User.getEmail();
|
||||
}
|
||||
if (authentication.getPrincipal() instanceof String) {
|
||||
return (String) authentication.getPrincipal();
|
||||
}
|
||||
|
@ -38,7 +38,7 @@
|
||||
<p:menuitem value="Quit" url="http://www.primefaces.org" icon="pi pi-times"/>
|
||||
|
||||
<f:facet name="options">
|
||||
<p:link href="/logout" value="Logout"/>
|
||||
<p:link href="/logout" value="Выход"/>
|
||||
</f:facet>
|
||||
</p:menubar>
|
||||
<div class="ui-fluid">
|
||||
|
@ -45,6 +45,8 @@
|
||||
</tr>
|
||||
<tr>
|
||||
<td>
|
||||
<a href="oauth2/authorize-client/google"
|
||||
class="list-group-item active">Войти с учетной записью Google</a>
|
||||
</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
|
@ -45,3 +45,5 @@ ng-tracker.debug_email=romanov73@gmail.com
|
||||
ng-tracker.use-https=false
|
||||
ng-tracker.check-run=false
|
||||
ng-tracker.driver-path=
|
||||
spring.security.oauth2.client.registration.google.client-id=128435862215-4ltm7dr6enb6sfll0qhkt6a1op9juve6.apps.googleusercontent.com
|
||||
spring.security.oauth2.client.registration.google.client-secret=W_B-KMpqsSdKahqFxpuK4OoT
|
||||
|
@ -34,6 +34,10 @@
|
||||
</div>
|
||||
</fieldset>
|
||||
</form>
|
||||
<h3>Login with:</h3>
|
||||
<p th:each="url : ${urls}">
|
||||
<a th:text="${url.key}" th:href="${url.value}">Client</a>
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
22
src/main/resources/templates/oauth_login.html
Normal file
22
src/main/resources/templates/oauth_login.html
Normal file
@ -0,0 +1,22 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
|
||||
<title>Oauth2 Login</title>
|
||||
<link rel="stylesheet"
|
||||
href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css"/>
|
||||
</head>
|
||||
|
||||
<body>
|
||||
<div class="container">
|
||||
<div class="col-sm-3 well">
|
||||
<h3>Login with:</h3>
|
||||
<div class="list-group">
|
||||
<p th:each="url : ${urls}">
|
||||
<a th:text="${url.key}" th:href="${url.value}" class="list-group-item active">Client</a>
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
Loading…
Reference in New Issue
Block a user