Related
I'm Adding 3 Categories using Post Request and for every Category, 3 respective Courses are added to the same. Finally I need to get an array of Categories containing list of courses.
But while performing Test Driven Development using Mockito, I', recieving a null Pointer Exception with status code 400.
Kindly help me in the same.
Test.java
#RunWith(value = MockitoJUnitRunner.class)
#WebMvcTest(Controller.class)
class Test {
#Autowired
MockMvc mvc;
#MockBean
service s;
#MockBean
Controller cont;
#MockBean
StatusResultMatchers sr;
#org.junit.jupiter.api.Test
void catTest() throws Exception {
Course c1=new Course(1,"Technology",100,50,7415);
Course c2=new Course(2,"Technology",100,50,7415);
Course c3=new Course(3,"Technology",100,50,7415);
Course[] c= {c1,c2,c3};
List<Course> cl=new ArrayList<Course>();
cl.add(c1);
cl.add(c2);
cl.add(c3);
Category ca=new Category(7415,"java","very gud", cl);
when(s.getAllContents()).thenReturn(cl);
mvc.perform(get("/getcourse")).andExpect(sr.is2xxSuccessful()).andReturn();
}
}
Controller.java
#RestController
public class Controller {
#Autowired
private service cs;
#RequestMapping(value="/addcat", method=RequestMethod.POST)
public void addcat(#RequestBody Category[] categ) throws Exception{
for(int i=0;i<3;i++)
cs.cat[i]=categ[i];
}
#RequestMapping(value="/addcour", method=RequestMethod.POST)
public void addcour(#RequestBody Course[] cour) {
for(Category c:cs.cat) {
cs.co=null;
for(int i=0;i<3;i++) {
if(cour[i].getCategoryId()==c.getCategoryId()) {
cs.co.add(cour[i]);
c.setCourseList(cs.co);
}
}
}
}
#RequestMapping(value="/getcat", method=RequestMethod.GET)
public #ResponseBody Category[] getcat(){
return cs.getAllCategories();
}
#RequestMapping(value="/getcourse", method=RequestMethod.GET)
public #ResponseBody List<Course> getcourse(#RequestBody Map<Category,List<Course> > cour){
return cs.getAllContents();
}
}
Service.java
#Service
public class service {
public List<Course> co=new ArrayList<Course>();
public Category[] cat=new Category[3];
public List<Course> getAllContents() {
return co;
}
public Category[] getAllCategories() {
return cat;
}
}
Test Output
MockHttpServletRequest:
HTTP Method = GET
Request URI = /getcourse
Parameters = {}
Headers = []
Body = <no character encoding set>
Session Attrs = {}
Handler:
Type = com.example.demo.controller.Controller$MockitoMock$138133307
Method = com.example.demo.controller.Controller$MockitoMock$138133307#getcourse(Map)
Async:
Async started = false
Async result = null
Resolved Exception:
Type = org.springframework.http.converter.HttpMessageNotReadableException
ModelAndView:
View name = null
View = null
Model = null
FlashMap:
Attributes = null
MockHttpServletResponse:
Status = 400
Error message = null
Headers = []
Content type = null
Body =
Forwarded URL = null
Redirected URL = null
Cookies = []
2020-06-03 17:38:59.573 INFO 26360 --- [extShutdownHook] o.s.s.concurrent.ThreadPoolTaskExecutor : Shutting down ExecutorService 'applicationTaskExecutor'
I have updated my code. Now, NullPOinterException is not there. But I'm getting an empty list "ActualCourse".
Please find d code below:
Test.java
#RunWith(value = MockitoJUnitRunner.class)
#WebMvcTest(Controller.class)
class Test {
#Autowired
MockMvc mvc;
#MockBean
service testService;
#MockBean
Controller targetController;
#Before
public void setup() {
MockitoAnnotations.initMocks(this);
}
#org.junit.jupiter.api.Test
void catTest() throws Exception {
// Mock Data
Course c1=new Course(1,"Technology",100,50,7415);
Course c2=new Course(2,"Technology",100,50,7415);
Course c3=new Course(3,"Technology",100,50,7415);
List<Course> expectedCourse=new ArrayList<Course>();
expectedCourse.add(c1);
expectedCourse.add(c2);
expectedCourse.add(c3);
Category expectedCategory=new Category(7415,"java","very gud", expectedCourse);
when(testService.addcour()).thenReturn(expectedCourse);
List<Course> actualCourse = targetController.addcour();
assertEquals(expectedCourse,actualCourse);
}
Controller.java
#RestController
public class Controller {
#Autowired
private service cs;
#RequestMapping(value="/addcat", method=RequestMethod.POST)
public List<Category> addcat(#RequestBody Category[] categ) throws Exception{
return cs.addcat(categ);
}
#RequestMapping(value="/addcour", method=RequestMethod.POST)
public List<Course> addcour() {
return cs.addcour();
}
#RequestMapping(value="/getcat", method=RequestMethod.GET)
public #ResponseBody List<Category> getcat(){
return cs.getAllCategories();
}
#RequestMapping(value="/getcourse", method=RequestMethod.GET)
public #ResponseBody List<Course> getcourse(){
return cs.getAllCourses();
}
}
Service.java
#Service
public class service {
public List<Category> cat=new ArrayList<Category>();
public List<Course> c=new ArrayList<Course>();
List<Course> empty=new ArrayList<Course>();
List<Category> category=new ArrayList<Category>();
public List<Category> addcat(Category[] categ) {
int flagcat=0,flagcourse=0;
Category c1=new Category(7415,"Technology","Java",empty);
Category c2=new Category(2,"Technology","Java",empty);
Category c3=new Category(7314,"Technology","Java",empty);
Category c4=new Category(4,"Technology","Java",empty);
Category c5=new Category(8415,"Technology","Java",empty);
Category c6=new Category(6,"Technology","Java",empty);
category=Arrays.asList(c1,c2,c3,c4,c5,c6);
Iterator icat=category.iterator();
Iterator icourse=c.iterator();
Object ncourse=new Object();
Object ncat=new Object();
while(icat.hasNext()) {
List<Course> co=new ArrayList<Course>();
flagcat++;
flagcourse=0;
ncat=icat.next();
while(icourse.hasNext()) {
ncourse=icourse.next();
if(((Category) ncourse).getCategoryId()==((Category) ncat).getCategoryId()) {
flagcourse++;
co.add((Course) ncourse);
if(flagcourse==3) {
((Category) ncat).setCourseList(co);
break;
}
}
}
cat.add((Category) icat);
if(flagcat==3) {
break;
}
}
return cat;
}
public List<Course> addcour() {
Course c1=new Course(1,"Technology",100,50,7415);
Course c2=new Course(2,"Technology",100,50,7415);
Course c3=new Course(3,"Technology",100,50,7415);
Course c4=new Course(4,"Technology",100,50,7314);
Course c5=new Course(5,"Technology",100,50,7314);
Course c6=new Course(6,"Technology",100,50,7314);
Course c7=new Course(7,"Technology",100,50,8415);
Course c8=new Course(8,"Technology",100,50,8415);
Course c9=new Course(9,"Technology",100,50,8415);
Course c10=new Course(10,"Technology",100,50,8415);
List<Course> c=Arrays.asList(c1,c2,c3,c4,c5,c6,c7,c8,c9,c10);
return c;
}
public List<Course> getAllCourses() {
return c;
}
public List<Category> getAllCategories() {
return cat;
}
}
Output
org.opentest4j.AssertionFailedError: expected: <[com.example.demo.Course#6ecc02bb, com.example.demo.Course#31973858, com.example.demo.Course#65514add]> but was: <[]>
at org.junit.jupiter.api.AssertionUtils.fail(AssertionUtils.java:55)
at org.junit.jupiter.api.AssertionUtils.failNotEqual(AssertionUtils.java:62)
at org.junit.jupiter.api.AssertEquals.assertEquals(AssertEquals.java:182)
at org.junit.jupiter.api.AssertEquals.assertEquals(AssertEquals.java:177)
at org.junit.jupiter.api.Assertions.assertEquals(Assertions.java:1124)
at com.example.demo.test.Test.catTest(Test.java:75)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:567)
at org.junit.platform.commons.util.ReflectionUtils.invokeMethod(ReflectionUtils.java:686)
at org.junit.jupiter.engine.execution.MethodInvocation.proceed(MethodInvocation.java:60)
at org.junit.jupiter.engine.execution.InvocationInterceptorChain$ValidatingInvocation.proceed(InvocationInterceptorChain.java:131)
at org.junit.jupiter.engine.extension.TimeoutExtension.intercept(TimeoutExtension.java:149)
at org.junit.jupiter.engine.extension.TimeoutExtension.interceptTestableMethod(TimeoutExtension.java:140)
at org.junit.jupiter.engine.extension.TimeoutExtension.interceptTestMethod(TimeoutExtension.java:84)
at org.junit.jupiter.engine.execution.ExecutableInvoker$ReflectiveInterceptorCall.lambda$ofVoidMethod$0(ExecutableInvoker.java:115)
at org.junit.jupiter.engine.execution.ExecutableInvoker.lambda$invoke$0(ExecutableInvoker.java:105)
at org.junit.jupiter.engine.execution.InvocationInterceptorChain$InterceptedInvocation.proceed(InvocationInterceptorChain.java:106)
at org.junit.jupiter.engine.execution.InvocationInterceptorChain.proceed(InvocationInterceptorChain.java:64)
at org.junit.jupiter.engine.execution.InvocationInterceptorChain.chainAndInvoke(InvocationInterceptorChain.java:45)
at org.junit.jupiter.engine.execution.InvocationInterceptorChain.invoke(InvocationInterceptorChain.java:37)
at org.junit.jupiter.engine.execution.ExecutableInvoker.invoke(ExecutableInvoker.java:104)
at org.junit.jupiter.engine.execution.ExecutableInvoker.invoke(ExecutableInvoker.java:98)
at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.lambda$invokeTestMethod$6(TestMethodTestDescriptor.java:212)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.invokeTestMethod(TestMethodTestDescriptor.java:208)
at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:137)
at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:71)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$5(NodeTestTask.java:135)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$7(NodeTestTask.java:125)
at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:135)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:123)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:122)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:80)
at java.base/java.util.ArrayList.forEach(ArrayList.java:1507)
at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:38)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$5(NodeTestTask.java:139)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$7(NodeTestTask.java:125)
at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:135)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:123)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:122)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:80)
at java.base/java.util.ArrayList.forEach(ArrayList.java:1507)
at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:38)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$5(NodeTestTask.java:139)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$7(NodeTestTask.java:125)
at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:135)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:123)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:122)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:80)
at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.submit(SameThreadHierarchicalTestExecutorService.java:32)
at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor.execute(HierarchicalTestExecutor.java:57)
at org.junit.platform.engine.support.hierarchical.HierarchicalTestEngine.execute(HierarchicalTestEngine.java:51)
at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:229)
at org.junit.platform.launcher.core.DefaultLauncher.lambda$execute$6(DefaultLauncher.java:197)
at org.junit.platform.launcher.core.DefaultLauncher.withInterceptedStreams(DefaultLauncher.java:211)
at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:191)
at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:137)
at org.eclipse.jdt.internal.junit5.runner.JUnit5TestReference.run(JUnit5TestReference.java:89)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:41)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:542)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:770)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:464)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:210)
It seems you have some design issues in your code. In your controller, the getcourse method is receiving a request body Map<Category,List<Course> > cour, but the HTTP method is a GET, you're not supposed to send data in a GET method (check this answer and this for more context).
On the other side, your getcourse is not using the cour parameter, so refactor this method as:
#RequestMapping(value="/getcourse", method=RequestMethod.GET)
public #ResponseBody List<Course> getcourse(){
return cs.getAllContents();
}
Let me know if it works.
I am getting the Response JSON (for JWT token request) as below:
{
"access_token": "<JWT Access Token>",
"token_type": "bearer",
"refresh_token": "<JWT Refresh Token>",
"expires_in": 3599,
"scope": "read write trust",
"DateOfBirth": "01-01-1990",
"Address_Line_1": "ABCD Andrews Dr, Apt 111",
"PAN_Number": "12345ABCD",
"Address_Line_2": "Dublin, CA 94588",
"jti": "e6a19730-e4e5-4cec-bf59-bd90ca1acc34"
}
I want to modify it (by removing a few elements) to:
{
"access_token": "<JWT Access Token>",
"token_type": "bearer",
"refresh_token": "<JWT Refresh Token>",
"expires_in": 3599,
"scope": "read write trust",
"jti": "e6a19730-e4e5-4cec-bf59-bd90ca1acc34"
}
I tried to used ResponseBodyAdvice as adviced by a few. But issue is response body object (available as public Object beforeBodyWrite(Object body ...) is of object type - "org.springframework.security.oauth2.common.DefaultOAuth2AccessToken" and not JSON. I am not sure how i can manipulate DefaultOAuth2AccessToken to remove the additional elements.
Could anybody please help me?
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {
#Autowired
#Qualifier("authenticationManagerBean")
private AuthenticationManager authenticationManager;
#Override
public void configure(final AuthorizationServerSecurityConfigurer oauthServer) throws Exception {
oauthServer.tokenKeyAccess("permitAll()").checkTokenAccess("isAuthenticated()");
}
#Override
public void configure(ClientDetailsServiceConfigurer configurer) throws Exception {
configurer
.inMemory()
.withClient(CLIEN_ID)
.secret(passwordEncoder().encode(CLIENT_SECRET))
.authorizedGrantTypes(GRANT_TYPE_PASSWORD, REFRESH_TOKEN)
.scopes(SCOPE_READ, SCOPE_WRITE, TRUST)
.accessTokenValiditySeconds(ACCESS_TOKEN_VALIDITY_SECONDS)
.refreshTokenValiditySeconds(REFRESH_TOKEN_VALIDITY_SECONDS);
}
#Bean
#Primary
public DefaultTokenServices tokenServices() {
final DefaultTokenServices defaultTokenServices = new DefaultTokenServices();
defaultTokenServices.setTokenStore(tokenStore());
defaultTokenServices.setSupportRefreshToken(true);
return defaultTokenServices;
}
#Override
public void configure(final AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
TokenEnhancerChain tokenEnhancerChain = new TokenEnhancerChain();
tokenEnhancerChain.setTokenEnhancers(Arrays.asList(tokenEnhancer(), accessTokenConverter()));
endpoints.tokenStore(tokenStore()).tokenEnhancer(tokenEnhancerChain).authenticationManager(authenticationManager);
}
#Bean
public TokenEnhancer tokenEnhancer() {
return new CustomTokenEnhancer();
}
}
public class CustomTokenEnhancer implements TokenEnhancer {
#Override
public OAuth2AccessToken enhance(OAuth2AccessToken oAuth2AccessToken, OAuth2Authentication oAuth2Authentication) {
Map<String, Object> additionalInfo = new HashMap<>();
additionalInfo.put("DateOfBirth", oAuth2Authentication.getOAuth2Request().getRequestParameters().get("dob"));
additionalInfo.put("PAN_Number", oAuth2Authentication.getOAuth2Request().getRequestParameters().get("pan"));
additionalInfo.put("Address_Line_1", oAuth2Authentication.getOAuth2Request().getRequestParameters().get("addr1"));
additionalInfo.put("Address_Line_2", oAuth2Authentication.getOAuth2Request().getRequestParameters().get("addr2"));
((DefaultOAuth2AccessToken) oAuth2AccessToken).setAdditionalInformation(additionalInfo);
return oAuth2AccessToken;
}
}
#ControllerAdvice
public class ResponseJSONAdvice implements ResponseBodyAdvice<Object> {
#Override
public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
return true;
}
#Override
public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class<? extends
HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
/*
Logic to remove additional elements from response JSON.
But Object body is of type org.springframework.security.oauth2.common.DefaultOAuth2AccessToken and not JSON!!
*/
return body;
}
}
Keep using ResponseBodyAdvice, first define a class which have all field you want to show. Then make method beforeBodyWrite return that class. In beforeBodyWrite method you want to set field of defined class by value of body, then return it.
Sorry i don't good at english, ask me if u don't get it ;)
public BaseResponse beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
BaseResponse res = new BaseResponse();
res.setResponseStatusCode(StatusResponse.SUCCESS.getCode());
res.setResponseStatusMessage(StatusResponse.SUCCESS.getName());
res.setContent(body);
return res;
}
From my point of view you have to adjust your token enhance that you configure in your AuthorizationServerConfigurerAdapter
in the method
public void configure(
AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
TokenEnhancerChain tokenEnhancerChain = new TokenEnhancerChain();
tokenEnhancerChain.setTokenEnhancers(
Arrays.asList(tokenEnhancer(), accessTokenConverter()));
endpoints.tokenStore(tokenStore())
.tokenEnhancer(tokenEnhancerChain)
.authenticationManager(authenticationManager);
}
you can set your custom enhance or configure one. This should allow you to turn on or off what is send with the token
It worked for me:
#Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
final TokenEnhancerChain tokenEnhancerChain = new TokenEnhancerChain(); tokenEnhancerChain.setTokenEnhancers(Arrays.asList(accessTokenConverter(), tokenEnhancer()));
endpoints.tokenStore(tokenStore())
.tokenEnhancer(tokenEnhancerChain)
.authenticationManager(authenticationManager);
}
I have separate authorization server and resource server.
Authorization server is pointing to a separate database. I haves used CustomUserDetailService for user related information.
I have used CustomTokenEnhancer to have additional information apart from the token in the response.
#Configuration
public class OAuth2Configuration {
#Configuration
#EnableAuthorizationServer
protected static class AuthorizationServerConfiguration extends AuthorizationServerConfigurerAdapter implements EnvironmentAware {
private static final String ENV_OAUTH = "authentication.oauth.";
private static final String PROP_CLIENTID = "clientid";
private static final String PROP_SECRET = "secret";
private static final String PROP_TOKEN_VALIDITY_SECONDS = "tokenValidityInSeconds";
private RelaxedPropertyResolver propertyResolver;
#Autowired
private DataSource dataSource;
#Autowired
private CustomUserDetailService userDetailsService;
#Bean
public TokenStore tokenStore() {
return new CustomTokenStore(dataSource);
}
#Autowired
#Qualifier("authenticationManagerBean")
private AuthenticationManager authenticationManager;
#Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints)
throws Exception {
endpoints
.tokenStore(tokenStore())
.userDetailsService(userDetailsService)
.tokenEnhancer(tokenEnhancer())
.accessTokenConverter(accessTokenConverter())
.authenticationManager(authenticationManager);
}
#Bean
public TokenEnhancer tokenEnhancer() {
return new CustomTokenEnhancer();
}
#Bean
public DefaultAccessTokenConverter accessTokenConverter() {
return new DefaultAccessTokenConverter();
}
#Override
public void configure(AuthorizationServerSecurityConfigurer oauthServer)
throws Exception {
oauthServer
.tokenKeyAccess("permitAll()")
.checkTokenAccess("isAuthenticated()");
}
}
}
CustomUserDetailService Class:
#Service
public class CustomUserDetailService implements UserDetailsService {
#Autowired
private AccountRepository accountRepository;
#Override
public UserDetails loadUserByUsername(String username) {
Account account = accountRepository.getByEmail(username);
if(account == null) {
throw new UsernameNotFoundException(username);
}
return new MyUserPrincipal(account);
}
}
CustomTokenEnhancer Class:
public class CustomTokenEnhancer implements TokenEnhancer {
#Override
public OAuth2AccessToken enhance(OAuth2AccessToken accessToken, OAuth2Authentication authentication) {
MyUserPrincipal user = (MyUserPrincipal) authentication.getPrincipal();
final Map<String, Object> additionalInfo = new HashMap<>();
additionalInfo.put("user_information", user.getAccount());
((DefaultOAuth2AccessToken) accessToken).setAdditionalInformation(additionalInfo);
return accessToken;
}
}
Request/Response
http://localhost:9191/authserver/oauth/token
{
"access_token": "fddb571e-224e-4cd7-974e-65104dd24b41",
"token_type": "bearer",
"refresh_token": "eb412b00-9e4e-4d6c-86d8-324d999b5f08",
"expires_in": 100,
"scope": "read write",
"account_information": {
"id": 14,
"firstname": "name",
"lastname": "lastname",
}
}
At resource server side, I have used RemoteTokenSerice to verify the the token presented by user is valid or not.
#Configuration
#EnableResourceServer
public class OAuthResourceConfig extends ResourceServerConfigurerAdapter {
private TokenExtractor tokenExtractor = new BearerTokenExtractor();
#Override
public void configure(HttpSecurity http) throws Exception {
http.addFilterAfter(new OncePerRequestFilter() {
#Override
protected void doFilterInternal(HttpServletRequest request,
HttpServletResponse response, FilterChain filterChain)
throws ServletException, IOException {
if (tokenExtractor.extract(request) == null) {
SecurityContextHolder.clearContext();
}
filterChain.doFilter(request, response);
}
}, AbstractPreAuthenticatedProcessingFilter.class);
http.csrf().disable();
http.authorizeRequests().anyRequest().authenticated();
}
#Bean
public AccessTokenConverter accessTokenConverter() {
return new DefaultAccessTokenConverter();
}
#Bean
#Primary
public RemoteTokenServices remoteTokenServices(final #Value("${auth.server.url}") String checkTokenUrl,
final #Value("${auth.server.clientId}") String clientId,
final #Value("${auth.server.clientsecret}") String clientSecret) {
final RemoteTokenServices remoteTokenServices = new RemoteTokenServices();
remoteTokenServices.setCheckTokenEndpointUrl(checkTokenUrl+"?name=value");
remoteTokenServices.setClientId(clientId);
remoteTokenServices.setClientSecret(clientSecret);
remoteTokenServices.setAccessTokenConverter(accessTokenConverter());
return remoteTokenServices;
}
}
So It is working properly and when I make a request to resource server with token, it processes the request if the token is valid. My question is I want to get Account object in resource server. I tried with below:
Account account = (Account)SecurityContextHolder.getContext().getAuthentication().getPrincipal()
But it gives string and not the complete user define object and hence it throws the exception.How to get Account object in any controller in Resource server?
{
"timestamp": 1499334657703,
"status": 500,
"error": "Internal Server Error",
"exception": "java.lang.ClassCastException",
"message": "java.lang.String cannot be cast to Account",
"path": "/secure"
}
I tried with link but is it possible to inject two token services, RemoteTokenService and CustomUserInfoTokenServices both?
Also I think here spring makes internal call from Resource Server to Authorization Server (http://localhost:9191/authserver/oauth/check_token?token=d8dae984-7bd8-4aab-9990-a2c916dfe667) to validate the token.
Is there any way I can get those information in controller without calling this endpoint again.
Response:
{
"exp": 1499333294,
"account_information": {
"accountid": 14,
"firstname": "fname",
"lastname": "lname",
},
"user_name": "abc#abc.com",
"client_id": "clientId",
"scope": [
"read",
"write"
]
}
I have overridden below method and added some logic.
public class CustomAccessTokenConverter extends DefaultAccessTokenConverter{
private UserAuthenticationConverter userTokenConverter = new DefaultUserAuthenticationConverter();
#Override
public OAuth2Authentication extractAuthentication(Map<String, ?> map) {
Map<String, String> parameters = new HashMap<String, String>();
#SuppressWarnings("unchecked")
Set<String> scope = new LinkedHashSet<String>(map.containsKey(SCOPE) ? (Collection<String>) map.get(SCOPE)
: Collections.<String>emptySet());
Authentication user = userTokenConverter.extractAuthentication(map);
String clientId = (String) map.get(CLIENT_ID);
parameters.put(CLIENT_ID, clientId);
parameters.put("account_information", String.valueOf((((Map) map.get("account_information")).get("accountid"))));
#SuppressWarnings("unchecked")
Set<String> resourceIds = new LinkedHashSet<String>(map.containsKey(AUD) ? (Collection<String>) map.get(AUD)
: Collections.<String>emptySet());
Map<String, Serializable> extensions = new HashMap<String, Serializable>();
extensions.put("account_information", (HashMap) map.get("account_information"));
OAuth2Request request = new OAuth2Request(parameters, clientId, null, true, scope, resourceIds, null, null,
extensions);
return new OAuth2Authentication(request, user);
}
}
Resource Server Class
#Bean
public AccessTokenConverter accessTokenConverter() {
//return new DefaultAccessTokenConverter();
return new CustomAccessTokenConverter();
}
#Bean
#Primary
public RemoteTokenServices remoteTokenServices(final #Value("${auth.server.url}") String checkTokenUrl,
final #Value("${auth.server.clientId}") String clientId,
final #Value("${auth.server.clientsecret}") String clientSecret) {
final RemoteTokenServices remoteTokenServices = new RemoteTokenServices();
remoteTokenServices.setCheckTokenEndpointUrl(checkTokenUrl+"?name=value");
remoteTokenServices.setClientId(clientId);
remoteTokenServices.setClientSecret(clientSecret);
remoteTokenServices.setAccessTokenConverter(accessTokenConverter());
return remoteTokenServices;
}
Now I can get additional information in controller.
OAuth2Authentication authentication = (OAuth2Authentication)SecurityContextHolder.getContext().getAuthentication();
Map<String, Serializable> map = authentication.getOAuth2Request().getExtensions();
I use in this way.
after call /oauth/token, I can get below, and member_id is additional field I added.
{
"access_token": "this is access token",
"token_type": "bearer",
"refresh_token": this is refreshtoken",
"expires_in": 3599,
"scope": "web",
"member_id": "d2lsbGlhbQ",
"jti": "79b9b523-921d-45c1-ba97-d3565f1d68b7"
}
after decode the access token, I can see this custom field member_id in it.
below are what I do in my Resource Server.
Declear Bean DefaultTokenService in configuration class
#Bean
#Primary
public DefaultTokenServices tokenServices() throws IOException {
DefaultTokenServices defaultTokenServices = new DefaultTokenServices();
defaultTokenServices.setTokenStore(tokenStore());
return defaultTokenServices;
}
here I inject resource into my controller.
#Autowired
private ResourceServerTokenServices resourceServerTokenServices;
#GetMapping("/addition")
public Map<String, Object> addition() {
Map<String, Object> response = new HashMap<>();
response.put("member_id", resourceServerTokenServices.readAccessToken(((OAuth2AuthenticationDetails) SecurityContextHolder.getContext().getAuthentication().getDetails()).getTokenValue()).getAdditionalInformation().get("member_id"));
return response;
}
then I call this /addition, I can see the response.
{
"member_id": "d2lsbGlhbQ"
}
I'm a newer to oAuth2 with JWT, so I have do some research on internet, but cannot find a sensitive method to get it from resource server. so I try some method to get this. hope it works.
I have the following controller logic. However, if I navigate to a non-existing page (e.g. /random-page), I end up with a TemplateInputException. How can I catch this and go to the 404 page?
#RequestMapping(value = { "{path:(?!resources|error).*$}", "{path:(?!resources|error).*$}/**" }, headers = "Accept=text/html")
public String index(final HttpServletRequest request) {
try {
String path = (String) request.getAttribute(
HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE);
return path.split("/")[1];
} catch (Exception e) {
log.error("Failed to render the page. {}",e);
return "error/general";
}
}
Thymeleaf seems to be ignoring the ExceptionHandler:
#ExceptionHandler(Exception.class)
public ModelAndView handleAllException(Exception ex) {
ModelAndView model = new ModelAndView("error/generic_error");
model.addObject("errMsg", "this is Exception.class");
return model;
}
My workaround this problem for spring-boot (exception is view with message param):
#Controller
public class ErrorController implements org.springframework.boot.autoconfigure.web.ErrorController {
private static final String ERROR_PATH = "/error";
#Autowired
private ErrorAttributes errorAttributes;
#Override
public String getErrorPath() {
return ERROR_PATH;
}
#RequestMapping(ERROR_PATH)
public String error(HttpServletRequest request, Model model) {
Map<String, Object> errorMap = errorAttributes.getErrorAttributes(new ServletRequestAttributes(request), false);
String exception = (String) errorMap.get("exception");
if (exception != null && exception.contains("TemplateInputException")) {
errorMap.put("message", "Неверный запрос");
}
model.addAllAttributes(errorMap);
return "exception";
}
}
My problem is to how to call this. I could do
MyObject o = new MyObject();
myController.save(o, "value");
but this is not what I would like to do. I would like the MyObject to be in the request post body? How can this be done?
#Requestmapping(value="/save/{value}", method=RequestMethod.POST)
public void post(#Valid MyObject o, #PathVariable String value{
objectService.save(o);
}
Just to be clear I am talking about unit testing.
Edit:
#RequestMapping(value = "/", method = RequestMethod.POST)
public View postUser(ModelMap data, #Valid Profile profile, BindingResult bindingResult) {
if (bindingResult.hasErrors()) {
return dummyDataView;
}
data.put(DummyDataView.DATA_TO_SEND, "users/user-1.json");
profileService.save(profile);
return dummyDataView;
}
See sample code below that demonstrates unit testing a controller using junit and spring-test.
#RunWith(SpringJUnit4ClassRunner.class)
#TestExecutionListeners({
DependencyInjectionTestExecutionListener.class,
DirtiesContextTestExecutionListener.class,
TransactionalTestExecutionListener.class })
#Transactional
#ContextConfiguration(locations = {
"classpath:rest.xml"
})
public class ControllerTest{
private MockHttpServletRequest request;
private MockHttpServletResponse response;
#Autowired
private RequestMappingHandlerAdapter handlerAdapter;
#Autowired
private RequestMappingHandlerMapping handlerMapping;
#Before
public void setUp() throws Exception
{
this.request = new MockHttpServletRequest();
request.setContentType("application/json");
this.response = new MockHttpServletResponse();
}
#Test
public void testPost(){
request.setMethod("POST");
request.setRequestURI("/save/test"); //replace test with any value
final ModelAndView mav;
Object handler;
try{
MyObject o = new MyObject();
//set values
//Assuming the controller consumes json
ObjectMapper mapper = new ObjectMapper();
//set o converted as JSON to the request body
//request.setContent(mapper.writeValueAsString(o).getBytes());
request.setAttribute("attribute_name", o); //in case you are trying to set a model attribute.
handler = handlerMapping.getHandler(request).getHandler();
mav = handlerAdapter.handle(request, response, handler);
Assert.assertEquals(200, response.getStatus());
//Assert other conditions.
}
catch (Exception e)
{
}
}
}
You need to use RequestBody:
#Requestmapping(value="/save/{value}", method=RequestMethod.POST)
public void post(#RequestBody MyObject o, #PathVariable String value{
objectService.save(o);
}
general info about request body documentation : http://static.springsource.org/spring/docs/3.0.x/reference/mvc.html#mvc-ann-requestbody