I am using the Spring Boot MitreID OIDC application from here. This runs OK and I can login but there are no other options available to me:
I am trying to access it using simple-web-app. In simple-web-app I try to login using URI: http://localhost:8080/openid-connect-server-webapp/. This gives:
WARN : org.mitre.openid.connect.client.service.impl.DynamicServerConfigurationService -
Couldn't load configuration for http://localhost:8080/openid-connect-server-webapp/:
com.google.common.util.concurrent.UncheckedExecutionException:
org.springframework.web.client.HttpClientErrorException: 404
ERROR: org.mitre.openid.connect.client.OIDCAuthenticationFilter - No server
configuration found for issuer: http://localhost:8080/openid-connect-server-webapp/
EDIT: when I try http://localhost:8080 I get:
WARN : org.mitre.openid.connect.client.service.impl.WebfingerIssuerService - Webfinger
endpoint MUST use the https URI scheme, overriding by configuration
ERROR: org.mitre.openid.connect.client.OIDCAuthenticationFilter - No client
configuration found for issuer: http://localhost:8080/
Can anyone point me in the right direction?
FYI simple-web-app has only one java class:
package org.mitre.web;
import java.security.Principal;
import java.util.Locale;
import java.util.Set;
import javax.annotation.Resource;
import org.mitre.openid.connect.client.OIDCAuthenticationFilter;
import org.mitre.openid.connect.client.SubjectIssuerGrantedAuthority;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
/**
* Handles requests for the application home page.
*/
#Controller
public class HomeController {
private static final Logger logger = LoggerFactory.getLogger(HomeController.class);
// filter reference so we can get class names and things like that.
#Autowired
private OIDCAuthenticationFilter filter;
#Resource(name = "namedAdmins")
private Set<SubjectIssuerGrantedAuthority> admins;
/**
* Simply selects the home view to render by returning its name.
*/
#RequestMapping(value = "/", method = RequestMethod.GET)
public String home(Locale locale, Model model, Principal p) {
model.addAttribute("issuerServiceClass", filter.getIssuerService().getClass().getSimpleName());
model.addAttribute("serverConfigurationServiceClass", filter.getServerConfigurationService().getClass().getSimpleName());
model.addAttribute("clientConfigurationServiceClass", filter.getClientConfigurationService().getClass().getSimpleName());
model.addAttribute("authRequestOptionsServiceClass", filter.getAuthRequestOptionsService().getClass().getSimpleName());
model.addAttribute("authRequestUriBuilderClass", filter.getAuthRequestUrlBuilder().getClass().getSimpleName());
model.addAttribute("admins", admins);
return "home";
}
#RequestMapping("/user")
#PreAuthorize("hasRole('ROLE_USER')")
public String user(Principal p) {
return "user";
}
#RequestMapping("/open")
public String open(Principal p) {
return "open";
}
#RequestMapping("/admin")
#PreAuthorize("hasRole('ROLE_ADMIN')")
public String admin(Model model, Principal p) {
model.addAttribute("admins", admins);
return "admin";
}
#RequestMapping("/login")
public String login(Principal p) {
return "login";
}
}
MitreID is serving on root but sample app is calling on /openid-connect-server-webapp/
You'll want to change your sample app to point to the proper issuer....http://localhost:8080/ (maybe in the application.properties of your sample app?) Or your MitreID server is not configured properly (possibly for issuer property)
See http://localhost:8080/.well-known/openid-configuration for all the endpoints your sample app would hit
Related
I have been trying all possible urls but same error keeps showing. please help. thanks in advance
here is my controller
package com.springstad.stad.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.springstad.stad.entitites.Names;
import com.springstad.stad.services.NameService;
#RestController
public class MyController {
#Autowired
private NameService nameservice;
// get employee names
#RequestMapping(path="/Names",method = RequestMethod.GET)
public List<Names> getNames(){
return this.nameservice.getNames();
}
#RequestMapping(path="/names/{nameID}",method = RequestMethod.GET)
public Names getNames(#PathVariable("nameID") String nameID) {
return this.nameservice.getNames(Long.parseLong(nameID));
}
}
what proxy config must i do for the postman to get responses from the code? ive been using localhost:8080/Names as url
Assuming its Spring-Boot app, pls check for servlet: context-path in application.yml (or application.properties). Lets say its value is "app1", then try with following url
localhost:8080/app1/Names
So in my Spring controller, i have this route
#RequestMapping(value = "myroute", method = POST)
public String myRoute(HttpServletRequest) {
...
}
We use MockMvcBuilder to mock the POST calls.
MockHttpServletRequestBuilder post = post(myRouteUrl);
mockMvc.perform(post).andExpect(status().isOK());
Now if i just change post to get, the status back is still 200.
So how to verify GET method is failing ?
Using Java 1.8.
Thanks !
I got a HTTP error 405 when I tried the following. Is there something else missing from the example shown?
This is the controller class I used.
package demo;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import static org.springframework.web.bind.annotation.RequestMethod.GET;
#RestController
public class MyController {
#RequestMapping(value = "/myroute", method = GET)
public String myRoute(HttpServletRequest request) {
System.out.println("HERE");
return "good";
}
}
This is the test class I used.
package demo;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
#ExtendWith(MockitoExtension.class)
#WebMvcTest(MyController.class)
class MyControllerTest {
#Autowired
private MockMvc mockMvc;
#Test
void myRoute() throws Exception {
MockHttpServletRequestBuilder post = post("/myroute");
mockMvc.perform(post).andExpect(status().isOk());
}
}
Error Message:
Error message = Request method 'POST' not supported
Headers = [Allow:"GET"]
Content type = null
Body =
Forwarded URL = null
Redirected URL = null
Cookies = []
Status expected:<200> but was:<405>
Expected :200
Actual :405
I am creating a Rest controller in JAVA . When I run the application locally , I am able to do POST operations. Then I create a JAR and then deploy it on a server . Plz note that I am using Netflix Eureka for service discovery and zuul as API gateway . The application starts running fine on server and it is registered in Eureka server as well . But when I use POST service , its giving me error : 405 Method Post not supported .
Controller class
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.bp.budgetpulse.domain.FeedBackEmployeeDetails;
import com.bp.budgetpulse.service.FeedBackService;
#RestController
#RequestMapping(value = "/api/v1")
public class FeedBackController {
#SuppressWarnings("unused")
private final Logger logger = LoggerFactory.getLogger(FeedBackService.class);
#Autowired
private FeedBackService feedbackService;
/**
* This method to save the feedback details
*
* #param feedbackDetails
* #param userName
* #return response
*/
#RequestMapping(value = "/saveEmployeeFeedbackDetails", method = RequestMethod.POST)
public String saveEmployeeFeedbackDetails(#RequestBody FeedBackEmployeeDetails empFeedbackDetails) {
return feedbackService.saveEmployeeFeedbackDetails(empFeedbackDetails);
}
/**
*
* this method to get the feedback details
*
* #return feedback details
*/
#RequestMapping(value = "/getFeedBackDetails/{email}", method = RequestMethod.GET)
public FeedBackEmployeeDetails getFeedBackDetails(#PathVariable String email) {
return feedbackService.getFeedBackDetails(email);
}
}
POST method is supported in Netflix Eureka and ZUUL. Netflix Eureka and ZUUL do not impose any restriction on the API Methods. Here is a sample controller code that I have written that works without any issues in a Netflix Eureka and ZUUL environment:
import com.aj.gradingservice.model.Grade;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
#RestController
#RequestMapping("/")
public class GradeController {
private static final Logger logger = LoggerFactory.getLogger(GradeController.class);
#RequestMapping(value = "ping", method = RequestMethod.GET)
public ResponseEntity<Map<String, String>> ping() {
Map<String, String> response = new HashMap<>();
response.put("message", "pong");
return new ResponseEntity<>(response, HttpStatus.OK);
}
#RequestMapping(value = "grades", method = RequestMethod.GET)
public ResponseEntity<List<Grade>> getGrades() {
logger.info("In GradeController.getGrades(), fetching list of grades");
List<Grade> grades = new ArrayList<>();
grades.add(new Grade(1, "P001", "A+"));
grades.add(new Grade(2, "C001", "A"));
grades.add(new Grade(3, "M001", "B+"));
return new ResponseEntity<>(grades, HttpStatus.OK);
}
#RequestMapping(value = "grade", method = RequestMethod.POST,
consumes = MediaType.APPLICATION_JSON_VALUE,produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<Grade> createGrade(#RequestBody Grade grade) {
logger.info("Request received is: " + grade );
Grade gradeCreated = new Grade(grade.getId(),grade.getStudentId(),grade.getGrade());
return new ResponseEntity<>(gradeCreated, HttpStatus.OK);
}
}
I have written a blog post with the detailed explanation of setting up a Netflix Eureka and Zuul environment and there is end to end working code in GitHub. Please check: http://softwaredevelopercentral.blogspot.com/2018/02/spring-cloud-eureka-and-zuul.html
i'm new in Spring + MVC.
i've found a script and i could run some part of this script.
this script configuring spring mvc with no xml, inside java side.
i put all the jars into WEB-INF/lib.
ControllerConfiguration .java
package org.java.springmvc.bootstrap;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
#Configuration
#EnableWebMvc
#ComponentScan(basePackages = "org.java.springmvc.controller")
public class ControllerConfiguration {
#Bean
public InternalResourceViewResolver configureInternalResourceViewResolver() {
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setPrefix("/WEB-INF/views/");
resolver.setSuffix(".jsp");
return resolver;
}
}
WebAppInitializer.java
package org.java.springmvc.bootstrap;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration.Dynamic;
import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;
public class WebAppInitializer implements WebApplicationInitializer {
#Override
public void onStartup(final ServletContext servletContext) throws ServletException {
final AnnotationConfigWebApplicationContext root = new AnnotationConfigWebApplicationContext();
root.setServletContext(servletContext);
root.scan("org.java.springmvc.bootstrap");
root.refresh();
final Dynamic servlet = servletContext.addServlet("spring", new DispatcherServlet(root));
servlet.setLoadOnStartup(1);
servlet.addMapping("/*");
}
}
HomeController.java
package org.java.springmvc.controller;
import java.io.IOException;
import java.io.Writer;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
#Controller
public class HomeController {
#RequestMapping(value = "/")
public void home(final Writer writer)
throws IOException {
writer.append("<h2>Welcome, XML Free Spring MVC!</h2>");
}
#RequestMapping(value = "/giris")
public void giris(final Writer writer)
throws IOException {
writer.append("Giris");
}
}
FilmController.java
package org.java.springmvc.controller;
import java.io.IOException;
import java.io.Writer;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.java.springmvc.model.Film;
import org.java.springmvc.model.Film.FilmTurleri;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
#Controller
#RequestMapping("/film")
public class FilmController {
#RequestMapping(value = "filmler")
public void filmler(final Writer writer)
throws IOException {
writer.append("<html><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=ISO-8859-9\"><title>...Filmler...</title>");
writer.append("<script type=\"text/javascript\" src=\"/js/touch/sencha-touch-all.js\"></script>");
writer.append("<script type=\"text/javascript\" src=\"/js/film/filmler.js\"></script>");
writer.append("</head><body></body></html>");
}
#RequestMapping (value = "/filmleriGetir", method = RequestMethod.GET)
public #ResponseBody Map<String, List<Film>> FilmleriGetir() {
List<Film> movies = new ArrayList<Film>();
// For testing...
movies.add(new Film(0, "Birinci Film", "Birinci Yönetmen", 2015, FilmTurleri.Aksiyon));
movies.add(new Film(0, "İkinci Film", "İkinci Yönetmen", 2015, FilmTurleri.Komedi));
movies.add(new Film(0, "Üçüncü Film", "Üçüncü Yönetmen", 2015, FilmTurleri.Aile));
Map<String, List<Film>> resp = new HashMap<String, List<Film>>();
resp.put("filmListesi", movies);
return resp;
}
}
Film.java
package org.java.springmvc.model;
public class Film {
public int Id;
public String FilmAdi, Yonetmen;
public int CikisTarihi;
public FilmTurleri Turu;
public enum FilmTurleri {
Aksiyon, Komedi, Aile, Korku, Savas;
}
public Film(){
}
public Film(int id, String title, String director, int yearOfRelease, FilmTurleri tur)
{
super();
this.Id = id;
this.FilmAdi = title;
this.Yonetmen = director;
this.CikisTarihi = yearOfRelease;
this.Turu = tur;
}
//getter, settings method
}
i have two questions:
if i write "http://localhost:8080/SpringMVC/", the page displays.
But if i write "http://localhost:8080/SpringMVC/movies/index" i get this warning:
"WARNING: No mapping found for HTTP request with URI [/SpringMVC/WEB-INF/views/index.jsp] in DispatcherServlet with name 'spring'"
if i add a JSP page(Giris.jsp) under WebContent, i cannot display this page. must all page has a mapping? how can i display simple jsp page?
WARNING: No mapping found for HTTP request with URI [/SpringMVC/Giris.jsp] in DispatcherServlet with name 'spring'
EDIT:
i changed a little.
My project structure like this:
i get this error:
Failed to load resource:
http://localhost:8080/js/film/filmler.js
http://localhost:8080/js/touch/sencha-touch-all.js
i thought a logic like that:
- there will be a jsp file including "*.js" files. (filmler.jsp)
- there are some methods returning json object in those *.js files. (FilmleriGetir method)
any advice for this logic?
Regards.
In MovieController.java, you need to add '/'
:
#RequestMapping("/movies")
You are using servlet.addMapping("/*"); which means your org.springframework.web.servlet.DispatcherServlet i.e Spring will intercept every request that comes to your application. Now, you don't have any RequestMapping for Giris.jsp in any controller, so Spring is throwing error as: No mapping found for HTTP request with URI [/SpringMVC/Giris.jsp]
In order to show Giris.jsp page, your need to:
A] Add entry in/ make new controller with RequestMapping for 'Giris.jsp', and set view as 'Giris'
eg:
#Controller
public class MyController {
#RequestMapping(value = "/Giris.jsp")
public void home(final Writer writer)
throws IOException {
return 'Giris';
}
}
You would be better of using RequestMapping as /giris instead of /Giris.jsp, as it exposes that underlying technology is JSP.
B] place Giris.jsp file under /WEB-INF/views/ folder.
Understand how InternalResourceViewResolver works. Taking reference of your ControllerConfiguration, When a view name is returned for controller as 'Giris', InternalResourceViewResolver adds prefix and suffix as defined by you, and that page is shown. So, in case of view name 'Giris', page '/WEB-INF/views/'+ 'Giris' + '.jsp' will be rendered.
According to java naming convention, JSP (file) name should always begin with a lower-case letter. So use giris.jsp instead of Giris.jsp
EDIT(For modified question):
Failed to load resource: http://localhost:8080/js/film/filmler.js
Understand that, as DispatcherServlet is mapped to /*, every request that comes to your web-app, is handled by DispatcherServlet i.e Spring.
Whenever you application comes across url http://localhost:8080/js/film/filmler.js, it knows that DispatcherServlet will handle that url. DispatcherServlet checks if there is any RequestMapping for the url(in controller).
Now, when you add url
http://localhost:8080/js/film/filmler.js
there is no RequestMapping that would handle such kind of url, so you are getting a url.
For loading resources such as js files or image files, use mvc:resources.
eg:
For js files:
Put all your js files in directory /WEB-INF/js/.
Add mvc:resource mapping for js files in you configuration:
<mvc:resources mapping="/js/**" location="/WEB-INF/js/" />
Now you you will be able to access your js files. If Spring comes across url such as /js/film/filmler.js, it will know know from mvc:resource mapping, for where to look for that file.
Goof mvc:resource for tutorials.
In my Spring Security application, I am trying to return cookie 'remember_token' after successful login. My AuthenticanSuccessHandler class auto wires RememberMeService class to get 'token' value from database. But autowired reference rememberMeService returns null. I did mention #Component annotation for the class, but it did not change the result. Link to complete source code
FormAuthenticationSuccessHandler:
package com.fastcheck.timesheet.common.security;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;
import com.fastcheck.timesheet.common.services.RememberMeService;
#Component
public class FormAuthenticationSuccessHandler implements AuthenticationSuccessHandler
{
#Autowired
public RememberMeService rememberMeService;
#Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
Authentication authentication) throws IOException, ServletException
{
String username;
Object principal = authentication.getPrincipal();
if (principal instanceof UserDetails)
{
username = ((UserDetails)principal).getUsername();
}
else
{
username = principal.toString();
}
System.out.println("rememberMeService :"+rememberMeService);
if(rememberMeService != null)
{
Cookie cookie=new Cookie("remember_token",rememberMeService.getRememberMeToken(username));
cookie.setMaxAge(200);
response.addCookie(cookie);
}
response.setStatus(200);
response.sendRedirect("home");
}
}
What I understand from your code is that you are trying to achieve what spring security is created to do out-of-the-box for you.
If you implemented spring security properly, I don't see why remember-me token will not be stored automatically on the user's browser after a successful authentication as you are trying to do.
Remember token automatically sent to the browser. You don't need to send it separately. Would it be possible to provide cookie value returned by browser? otherwise please use below script to decode it.
String cookieAsPlainText = new String(Base64.decode(cookies[i].getValue());
cookieAsPlainText as plain value should be series:token format. Please let me know if this helps