Error creating bean with name 'webSecurityConfig - spring

When I run my spring boot application, I get the following error:
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'webSecurityConfig': Unsatisfied dependency expressed through field 'userDetailsService'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'org.springframework.security.core.userdetails.UserDetailsService' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {#org.springframework.beans.factory.annotation.Qualifier("userDetailsServiceImpl"), #org.springframework.beans.factory.annotation.Autowired(required=true)}
Please help me resolve this error...

Simply implement a userService as needed by the error.
You should really implement one according to your authentification behavior (for example find a user in your firm database). And add it to your Spring context (which is automatic for #Service in your componentScan).
package com.company.example; // TODO: change this according to your project
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.orm.ObjectRetrievalFailureException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.GrantedAuthorityImpl;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tudu.domain.Role;
import tudu.domain.User;
import tudu.service.UserService;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.Set;
/**
* An implementation of Spring Security's UserDetailsService.
*
* #author Julien Dubois
*/
#Service("userDetailsService")
public class UserDetailsServiceImpl implements UserDetailsService {
private final Log log = LogFactory.getLog(UserDetailsServiceImpl.class);
#Autowired
private UserService userService;
/**
* Load a user for Spring Security.
*/
#Transactional
public UserDetails loadUserByUsername(String login)
throws UsernameNotFoundException, DataAccessException {
login = login.toLowerCase();
if (log.isDebugEnabled()) {
log.debug("Security verification for user '" + login + "'");
}
User user;
try {
user = userService.findUser(login);
} catch (ObjectRetrievalFailureException orfe) {
throw new UsernameNotFoundException("User '" + login
+ "' could not be found.");
}
user.setLastAccessDate(Calendar.getInstance().getTime());
Set<Role> roles = user.getRoles();
Collection<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
for (Role role : roles) {
authorities.add(new GrantedAuthorityImpl(role.getRole()));
}
return new org.springframework.security.core.userdetails.User(login,
user.getPassword(), user.isEnabled(), true, true, true,
authorities);
}
}

Related

Parameter 1 of constructor in required a bean of type that could not be found

I've been stuck for a while now. I'm modifying my Spring Security project by adding Jwt. Currently, I'm trying to make the JwtEncoder and JwtDecoder work in SecurityConfig, I need RSAPrivateKey and RSAPublicKey for these methods. To get these Key-values I'm using a Record with #ConfigurationProperties annotation. But Getting this Record into the SecurtyConfig gives me some problems:
***************************
APPLICATION FAILED TO START
***************************
Description:
Parameter 1 of constructor in com.ssl.app.security.config.SecurityConfig required a bean of type 'com.ssl.app.security.config.RsaKeyProperties' that could not be found.
Action:
Consider defining a bean of type 'com.ssl.app.security.config.RsaKeyProperties' in your configuration.
This is my SecurtyConfig
import com.nimbusds.jose.jwk.JWK;
import com.nimbusds.jose.jwk.JWKSet;
import com.nimbusds.jose.jwk.RSAKey;
import com.nimbusds.jose.jwk.source.ImmutableJWKSet;
import com.nimbusds.jose.jwk.source.JWKSource;
import com.nimbusds.jose.proc.SecurityContext;
import com.ssl.app.security.filters.LoginAuthFilter;
import com.ssl.app.utility.ConsoleUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
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.configurers.oauth2.server.resource.OAuth2ResourceServerConfigurer;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.oauth2.jwt.JwtDecoder;
import org.springframework.security.oauth2.jwt.JwtEncoder;
import org.springframework.security.oauth2.jwt.NimbusJwtDecoder;
import org.springframework.security.oauth2.jwt.NimbusJwtEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
#Configuration
//#AllArgsConstructor
#EnableWebSecurity
//#EnableConfigurationProperties
public class SecurityConfig {
private final LoginAuthFilter loginAuthFilter;
private final RsaKeyProperties rsaKeyProperties;
public SecurityConfig(LoginAuthFilter loginAuthFilter, RsaKeyProperties rsaKeyProperties) {
this.loginAuthFilter = loginAuthFilter;
this.rsaKeyProperties = rsaKeyProperties;
}
#Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
return http
.csrf(csrf -> csrf.disable())
.authorizeRequests(auth -> auth
.anyRequest().authenticated()
)
.oauth2ResourceServer(OAuth2ResourceServerConfigurer::jwt) // get config_class :: method
.sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
.addFilterBefore(loginAuthFilter, UsernamePasswordAuthenticationFilter.class)
.build();
}
#Bean
JwtDecoder jwtDecoder() {
ConsoleUtil.PrintRow(this.getClass().getSimpleName(),"Decode publicKey", "true");
// Get public key and decode and return
return NimbusJwtDecoder.withPublicKey(rsaKeyProperties.publicKey()).build();
}
#Bean
JwtEncoder jwtEncoder() {
ConsoleUtil.PrintRow(this.getClass().getSimpleName(),"Encode jwt", true);
JWK jwk = new RSAKey.Builder(rsaKeyProperties.publicKey()).privateKey(rsaKeyProperties.privateKey()).build();
JWKSource<SecurityContext> jwks = new ImmutableJWKSet<>(new JWKSet(jwk));
return new NimbusJwtEncoder(jwks);
}
}
Record
import org.springframework.boot.context.properties.ConfigurationProperties;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
#ConfigurationProperties(prefix ="rsa")
public record RsaKeyProperties(RSAPublicKey publicKey, RSAPrivateKey privateKey) {
}
I tried adding #EnableConfigurationProperties, and EnableAutoConfiguration to the SecurtyConfig would work, but it has no effect. #Value annotation don't work either. The SecurityConfig required a bean, but what bean?
Maybe you should refer to this article
spring-security-jwt

Spring boot #RestController test code error

I created a test code for #RestController on the spring boot and this error occurs.
java.lang.IllegalStateException: Failed to load ApplicationContext
at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:132)
---------------------------------------------------------------------------
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'memberController' defined in file [C:\dev\react\Kculter\target\classes\com\prac\react\controller\MemberController.class]: Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.prac.react.service.MemberService' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {}
--------------------------------------------------------------------------------------------------
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.prac.react.service.MemberService' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {}
I see this problem even though I added #Service annotations to the MemberService class and #RestController annotations to the MemberController class.
How can I solve it?
I'll show my Test code, MemberCotroller, MemberService code below
MemberControllerTest.java
package com.prac.react.controller;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.MockMvc;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.prac.react.model.dto.Member;
import com.prac.react.service.MemberServiceTest;
#WebMvcTest(MemberController.class)
public class MemberControllerTest {
#Autowired
MockMvc mvc; // 가상의 http request를 테스트 할때 만들기 위해서 사용하는 인스턴스
#Autowired
ObjectMapper obm;
Logger logger = LoggerFactory.getLogger(MemberServiceTest.class);
#Test
#DisplayName("로그인 테스트 1 ") // 회원이 존재할때를 가장했을때를 위한 테스트 코드
void testSignInMember() throws Exception {
// given
Member mb = new Member(1, "hankgood95#gmail.com", "이욱재", true);
String requestBody = obm.writeValueAsString(mb);
mvc.perform(post("/member")
.content(requestBody)
.contentType(MediaType.APPLICATION_JSON))
.andExpect(status().isOk()) //status가 200이고
.andExpect(content().string(".com")) //content안에 .com이 있다면
.andDo(print()); //요청받은것들으 print 해라
}
}
MemberController.java
package com.prac.react.controller;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import com.prac.react.model.dto.Member;
import com.prac.react.service.MemberService;
/* 이파일은 회원가입,로그인,회원정보수정 등등
회원 정보와 관련된 일을 할때 들어올 Controller 입니다 */
#RestController
public class MemberController {
//로그를 찍어보기 위해서 만든 인스턴스
Logger logger = LoggerFactory.getLogger(MemberController.class);
//MemberService 의존성 주입을 위해 사용할 인스턴스
MemberService ms;
public MemberController(MemberService ms){
this.ms = ms; //의존성 주입
}
#PostMapping("member")
public Member SignInMember(#RequestBody Member member){
if(ms.checkMember(member.getEmail()) > 0){ //이미 우리 회원일때 접근
//이미 우리 회원이라면 여기서 얻은 Member 정보를 가지고 메인페이지로 이동을 해야한다.
member.setCheckMember(true);
return member;
}else{//처음 가입할때 접근
//우리 회원이 아니라면 이제 회원가입 페이지로 이동을 해야한다.
member.setCheckMember(false);
return member;
}
}
}
MemberService.java
package com.prac.react.service;
import org.springframework.stereotype.Service;
import com.prac.react.model.dao.MemberDao;
#Service
public class MemberService {
MemberDao md;
//MemberDao 인스턴스의 의존성 주입을 위해 생성자 안에서 집어 넣어주었습니다.
//여기서 주의해야할점은 의존성 주입이 하나 이상일땐 #Autowired 어노테이션을 꼭 넣어줘야만 합니다.
public MemberService(MemberDao md){
this.md = md;
}
public int checkMember(String email){
return md.checkMember(email);
}
}
When you using the test slice #WebMvcTest:
Regular #Component and #ConfigurationProperties beans are not scanned when the #WebMvcTest annotation is used.
This means your class annotated with #Service is also not configured.
You can use #MockBean to create a mock for this service.
Reference with Example: Spring Boot Reference

#Autowired and UnsatisfiedDependencyException in a junit test

i am writing a junit test that have to invoke some method from some autowired dependency which has to interact with Cassandra, but i am getting this exception:
[ERROR] Tests run: 1, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 0.21 s <<< FAILURE! - in unicon.mattheews.admin.service.repository.test.AdminUserRepositoryTests
[ERROR] testFindByUsername(unicon.mattheews.admin.service.repository.test.AdminUserRepositoryTests) Time elapsed: 0.001 s <<< ERROR!
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'unicon.mattheews.admin.service.repository.test.AdminUserRepositoryTests': Unsatisfied dependency expressed through field 'repository'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'unicon.matthews.admin.service.repository.AdminUserRepository' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'unicon.matthews.admin.service.repository.AdminUserRepository' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
This is the junit test:
import static org.hamcrest.Matchers.hasItems;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertThat;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.junit.Before;
import org.junit.ClassRule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.util.Version;
import org.springframework.test.context.junit4.SpringRunner;
import example.springdata.cassandra.util.CassandraKeyspace;
import unicon.matthews.admin.AdminUser;
import unicon.matthews.admin.service.repository.AdminUserRepository;
#RunWith(SpringRunner.class)
#SpringBootTest(classes = CassandraConfiguration.class)
public class AdminUserRepositoryTests {
#ClassRule public final static CassandraKeyspace CASSANDRA_KEYSPACE = CassandraKeyspace.onLocalhost().atLeast(Version.parse("3.0"));
#Autowired AdminUserRepository repository;
#Before
public void setUp() throws Exception {
repository.deleteAll();
}
#Test
public void testFindByUsername() {
try {
final String userName = "aironman";
AdminUser.Builder myBuilderAdmin = AdminUser.Builder.class.newInstance();
myBuilderAdmin.withId("id");
myBuilderAdmin.withEmailAddress("some#domain.com");
myBuilderAdmin.withOrgId("orgId");
myBuilderAdmin.withPassword("some-password");
myBuilderAdmin.withSuperAdmin(Boolean.TRUE);
myBuilderAdmin.withTenantId("tenantId");
myBuilderAdmin.withUserName(userName);
//que viene aqui exactamente?
Map<String, String> someMetadata = new HashMap<String, String>();
someMetadata.put("some-key","some-value");
myBuilderAdmin.withMetadata(someMetadata);
AdminUser myAdminUser = myBuilderAdmin.build();
repository.save(myAdminUser);
Optional<AdminUser> loadedUserName = repository.findByUsername(userName);
assertNotNull(loadedUserName);
// assertThat(repository.findOne(homer.id).isPresent(), is(true));
assertEquals("something went wrong!",userName,loadedUserName.get().getUsername());
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
System.out.println("Done testFindByUsername!");
}
}
AdminUserRepository looks like:
import java.util.Optional;
import org.springframework.data.cassandra.repository.Query;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
import unicon.matthews.admin.AdminUser;
#Repository
public interface AdminUserRepository extends CrudRepository<AdminUser, String> {
#Query("select * from AdminUser where username = ?0")
Optional<AdminUser> findByUsername(final String userName);
}
CassandraConfiguration looks like:
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.cassandra.config.SchemaAction;
import org.springframework.data.cassandra.config.java.AbstractCassandraConfiguration;
import org.springframework.data.cassandra.repository.config.EnableCassandraRepositories;
#Configuration
#EnableAutoConfiguration
class CassandraConfiguration {
#Configuration
#EnableCassandraRepositories
static class CassandraConfig extends AbstractCassandraConfiguration {
#Override
public String getKeyspaceName() {
return "example";
}
#Override
public SchemaAction getSchemaAction() {
return SchemaAction.RECREATE;
}
}
}
I understand that spring is trying to instantiate this AdminUserRepository class which is created using CrudRepository from spring-data project. It is supposed that if i mark this interface with #Repository, spring will instantiate the class within the spring context in order that another bean will be capable to autowire it within it, so, why spring is not able to instantiate the dependency?
AdminUserRepository interface is located within src/main/java and AdminUserRepositoryTests is located within src/test/java.
this is my actual pom.xml, please help.
Marking a Spring data repository with #Repository actually doesn't do anything. If you wan't to enable a CrudRepository you need to annotate your configuration with #EnableJpaRepositories. However, since you are using Cassandra I think it's more likely you want to be using a CassandraRepository ?
public interface AdminUserRepository extends CassandraRepository<AdminUser, String> {
#Query("select * from AdminUser where username = ?0")
Optional<AdminUser> findByUsername(final String userName);
}

No qualifying bean of type found for dependency

I´m tri to run a JUnit Test um my spring boot project i bilded like this:
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
import com.br.suppcomm.ocp.entity.Login;
public interface LoginDao extends JpaRepository<Login, Long>{
...
}
Service:
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.br.suppcomm.ocp.dao.CompanyDAO;
import com.br.suppcomm.ocp.dao.LoginDao;
import com.br.suppcomm.ocp.entity.Login;
#Service
public class LoginService {
#Autowired LoginDao loginDao;
#Autowired CompanyDAO companyDao;
public void save(Login login) {
loginDao.save(login);
}
public void delete(Login login) {
loginDao.delete(login);
}
public Login findById(Login login) {
return loginDao.findOne(login.getLoginId());
}
public Login findByEmail(Login login) {
return loginDao.findByEmail(login.getEmail());
}
public Login FindByLogin(Login login) {
return loginDao.FindByLogin(login);
}
public List<Login> getAll() {
return loginDao.findAll();
}
public Login getUserAccessLoginPass(String login, String password) {
return loginDao.getUserAccessLoginPass(login, password);
}
public void update(Login login) {
loginDao.save(login);
}
}
Test:
package com.example;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import com.br.suppcomm.ocp.service.LoginService;
#RunWith(SpringRunner.class)
#SpringBootTest
public class OcpJpaApplicationTests {
#Autowired LoginService loginService;
#Test
public void contextLoads() {
}
}
When I ran this code did show me the folow error.
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException:
Error creating bean with name 'loginService': Unsatisfied dependency
expressed through field 'loginDao': No qualifying bean of type
[com.br.suppcomm.ocp.dao.LoginDao] found for dependency
[com.br.suppcomm.ocp.dao.LoginDao]: expected at least 1 bean which
qualifies as autowire candidate for this dependency. Dependency
annotations:
{#org.springframework.beans.factory.annotation.Autowired(required=true)};
nested exception is
org.springframework.beans.factory.NoSuchBeanDefinitionException: No
qualifying bean of type [com.br.suppcomm.ocp.dao.LoginDao] found for
dependency [com.br.suppcomm.ocp.dao.LoginDao]: expected at least 1
bean which qualifies as autowire candidate for this dependency.
Dependency annotations:
{#org.springframework.beans.factory.annotation.Autowired(required=true)}
I dont know what happened!! Please.
Add #Repository your Interface
annotation , so that it can be Autowired.
#Repository
public interface LoginDao extends JpaRepository<Login, Long>{
}
It'll work that way!
Exception says that SPring is not able to find a qualifier, to Autowired something you need to sterotype it.
Please add the classes attribute to your #SpringBootTest annotation as follows:
#SpringBootTest(classes = { Application.class })
So that it will know that it has to do component scan, etc that you've specified on your Application class.
Add #Repository annotation on LoginDao
You need to add this annotation to your test:
#DataJpaTest
This will cause the Persistence slice of you application to be initialized.

How to create a google Oauth in spring?

I'm new to spring so bear with me :o
I'm using Spring Boot v1.1.8.RELEASE
I'm trying to get a working google Oauth connection with my website.
So I'm trying to get the spring-social-google working while the twitter & facebook one are working.
I read this http://gabiaxel.github.io/spring-social-google-reference/overview.html
I read the tutorial from Spring.io for the other providers(twitter & Facebook).
So here is the code I have :
package app.controllers;
import javax.inject.Inject;
import org.springframework.social.google.api.Google;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
#Controller
#RequestMapping("/google")
public class GoogleController {
private Google google;
#Inject
public GoogleController(Google google) {
this.google = google;
}
/**
*
* #param model
* #return
*/
#RequestMapping(method = RequestMethod.GET)
public String helloGoogle(Model model) {
if (!google.isAuthorized()) {
return "redirect:/connect/google";
}
model.addAttribute(google.plusOperations().getGoogleProfile());
return "testGoogle";
}
}
I have the files like for facebook in my templates a
googleConnect.html and a googleConnected.html.
Maven is importing correctly the dependencies
The application.properties have the secret and appid from a google
App I created
Here is the error I have :
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'googleController' defined in file [C:\Users\Antoine\Documents\NetBeansProjects\p0907931-cinemagik\app\target\classes\app\controllers\GoogleController.class]: Unsatisfied dependency expressed through constructor argument with index 0 of type [org.springframework.social.google.api.Google]: : No qualifying bean of type [org.springframework.social.google.api.Google] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {}; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [org.springframework.social.google.api.Google] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {}
The bean should be autowired like the other providers right ?
Thanks for your time.
edit :
This bean is working but I don't know how to implement it in my controller ?
#Configuration
public class SocialConfig {
#Inject
private Environment environment;
#Bean
public ConnectionFactoryLocator connectionFactoryLocator() {
ConnectionFactoryRegistry registry = new ConnectionFactoryRegistry();
registry.addConnectionFactory(new GoogleConnectionFactory(
environment.getProperty("superAPI"),
environment.getProperty("superSecret")));
return registry;
}
}
Spring Boot only has autoconfig support for Spring Social with Twitter, Facebook and LinkedIn (not Google). You can probably copy the code from the existing implementations and adapt it: https://github.com/spring-projects/spring-boot/tree/master/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/social.
package app.controllers;
import javax.inject.Inject;
import org.springframework.social.google.api.Google;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
#Controller
public class GoogleController {
private Google google;
#Inject
public GoogleController(Google google) {
this.google = google;
}
/**
*
* #param model
* #return
*/
#RequestMapping(method = RequestMethod.GET,value="/google")
public String helloGoogle(Model model) {
if (!google.isAuthorized()) {
return "redirect:/connect/google";
}
model.addAttribute(google.plusOperations().getGoogleProfile());
return "testGoogle";
}
}

Resources