resolving views in angularjs spring boot application with spring security - angularjs

I am trying to build an application with AngularJS 1.x, Spring Boot REST with Spring Security. Though I have intermediate knowledge on Spring REST itself, I am quite new to AngularJS and Spring Security.
I have given the github link of the application I have developed so far. Its in skeletal form still, and nothing is working:
https://github.com/imrnk/touchinghand
I will list down the problems and confusion I am having below:
1) I am using ui-router states to navigate from one state to another. So far I have identified two states: the "login" page and a link from there to "registration" page. Once the user will logged in, she will land to a dashboard. But this dashboard is yet to be created.
Now this login.html could be said as the entry point to the application. And when I type localhost:8080/ it should redirect to localhost:8080/login. Now I can see the page is redirecting correctly to the login.html but the templates I am using (login.template.html or register.template.html) inside login.html is not loading... However, when I am running through node js using browsersync, I see the page is loading with all the contents in it.
2) I tried disabling the spring security and then I see the login page is loaded correctly. So I guessed it could be a spring security issue, but what exactly is the issue I couldn't figure out.
My HttpSecurity configuration inside the implementation of WebSecurityConfigurerAdapter looks like this:
#Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/", "/login", "/register", "/**/*.css",
"/**/*.js", "/**/**/*.css", "/**/**/*.js",
"/**/**/**/*.css", "/**/**/**/*.js",
"/**/**/**/**/*.css", "/**/**/**/**/*.js", "/**/home.html", "**/login.html",
"**/**/login.template.html", "**/**/registration.template.html")
.permitAll().
regexMatchers("/registration*")
.permitAll()
.anyRequest().authenticated()
.and()
.formLogin().loginPage("/login").permitAll()
.and()
.logout().permitAll();
}
And my MvcConfig looks like this:
#Configuration
public class MvcConfig extends WebMvcConfigurerAdapter {
public void addResourceHandlers(ResourceHandlerRegistry registry) {
super.addResourceHandlers(registry);
registry.addResourceHandler("classpath:/resources/static/css/**")
.addResourceLocations("classpath:/resources/static/css/");
registry.addResourceHandler("classpath:/resources/js/**").addResourceLocations("classpath:/resources/js/");
registry.addResourceHandler("classpath:/resources/static/**")
.addResourceLocations("classpath:/resources/static/");
registry.addResourceHandler("classpath:/resources/static/templates/**")
.addResourceLocations("classpath:/resources/static/templates/");
}
#Override
public void addViewControllers(ViewControllerRegistry registry) {
super.addViewControllers(registry);
registry.addViewController("/").setViewName("forward:/login");
//registry.addViewController("/login").setViewName("forward:/login");
registry.addViewController("login.html");
//registry.addViewController("register").setViewName("registration");
// registry.addViewController("/registration.html");
//registry.addViewController("/dashboard").setViewName("dashboard");
//registry.addViewController("/dashboard.html");
}
#Override
public void configureViewResolvers(ViewResolverRegistry registry) {
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setPrefix("static/");
resolver.setSuffix(".html");
registry.viewResolver(resolver);
}
}
My LoginController class which anotated as #Controller has this:
#RequestMapping(value={"/"}, method = RequestMethod.GET)
public String showLogin(Model model){
model.addAttribute("user", new UserDTO());
return "/login";
}
3) I am quite confused between what should be the name of the resolved views and how that could map with the angular templates html.
I suspect, probably I am following a pure REST approach, and hanging in the middle with some aspect of Spring MVC and Spring REST. Introducing Spring Security also increased the problem for now.
I am also attaching the firefox developer network screenshot if that could help
enter image description here
Kindly help me out. Thanks.

Related

Configure http4 certificate in application.yml

I'm trying to move my http4 certificate configuration away from RouteBuilder class and to application.yml file. My code is exactly like the Java example on this page under the "Setting up SSL for HTTP Client - Programmatic Configuration of the Component": (https://camel.apache.org/http4.html#HTTP4-UsingtheJSSEConfigurationUtility). However, on the website there is no yml example, only the Java solution that I currently have and Spring DSL solution. Does anybody know how to translate the Java code to yml?
#Configuration
public class configureHttps4Certificate extends RouteBuilder {
#Override
public void configure() throws Exception {
KeyStoreParameters ksp = new KeyStoreParameters();
ksp.setResource("pathToResource");
ksp.setPassword("password");
TrustManagersParameters tmp = new TrustManagersParameters();
tmp.setKeyStore(ksp);
SSLContextParameters scp = new SSLContextParameters();
scp.setTrustManagers(tmp);
HttpComponent httpComponent = getContext().getComponent("https4", HttpComponent.class);
httpComponent.setSslContextParameters(scp);
}
}
If you use SpringBoot you can easily create Java configuration classes that automatically import values from property or YAML files just by using one annotation.
#ConfigurationProperties("app.config")
public class MyConfiguration
Check out this section of the SpringBoot documentation that describes this mechanism.

How to handle routing when both front end and back end are on the same server

I have a Spring boot and it has some services running on it. It also has a react view that has its own routing. Is this even possible, can I have a backend routing and front end routing within the same server?
Thanks
After some research, front-end routing is a misleading term, although it is being widely used. The routing needs to always go to the back-end, and the back-end decides what happens with the request. If React.js, Angular or any other front-end frameworks are handling routing, back-end needs to forward all the requests that are coming from the front-end to the front-end again, which is the HTML page that has the JS and CSS. To achieve this with spring framework, I used a tuckey filter to forward requests to the html page. The magic word is FORWARDING the request to the html page.
The urlrewrite.xml for the tuckey filter forwards the requests to the ui again, it looks like:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE urlrewrite PUBLIC "-//tuckey.org//DTD UrlRewrite 4.0//EN" "http://www.tuckey.org/res/dtds/urlrewrite4.0.dtd">
<!-- Configuration file for UrlRewriteFilter http://www.tuckey.org/urlrewrite/ -->
<urlrewrite>
<rule match-type="regex">
<name>Front-end forwarding</name>
<note>Forwarding all routes from the front-end to the ui controller</note>
<condition type="request-uri" operator="notequal">^\/([\-\w\.]+)([\-/\w\.]*)(\.([\-\w]+))$</condition>
<from>^\/ui\/([/\-\w]+)$</from>
<to type="forward" last="true">/ui</to> <!--This is where the ui controller is located-->
</rule>
</urlrewrite>
This is the tuckey filter java configurations:
#Component
public class TuckeyFilterConfigurations extends UrlRewriteFilter{
private static final String CONFIG_LOCATION = "classpath:/urlrewrite.xml";
#Value(CONFIG_LOCATION)
private Resource resource;
#Override
protected void loadUrlRewriter(FilterConfig filterConfig) throws ServletException {
try {
Conf conf = new Conf(filterConfig.getServletContext(), resource.getInputStream(), resource.getFilename(), "");
checkConf(conf);
} catch (IOException ex) {
throw new ServletException("Unable to load URL-rewrite configuration file from " + CONFIG_LOCATION, ex);
}
}
}
And finally, the controller that serves the html page simply looks like:
#Controller
public class UiController {
#RequestMapping("/ui")
public String entrance(){
return "index.html";
}
}
Yes you can have but it's always a good practice to have the routing logic at one place, as it helps a lot in troubleshooting the application once it's size grows.
How this would work, can you give an example? When I have a front end routing to a certain link, it is always directed to the backend. I know that there is the # routing, but I'm looking for a solution for the regular "/" routing?
You can use BrowserRouter or StaticRouter to achieve it. Here is the nice guide by React training team to implement Server Rendering using StaticRouter - Server Rendering with React.
Step 1 add below in your pom.xml:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<optional>true</optional>
</dependency>
Step 2, Please add below two lines in your application.properties :
#reload static content lively without reboot spring boot app
spring.devtools.livereload.enabled: true
#specify the static file location
spring.resources.static-locations: file:${your-frontend-file-root-location}

Spring boot & Spring Security : Forward the invalid urls

I work with spring boot, thymeleaf, spring security and angularjs
I want all url invalid to return to the home page.
The login page is managed by thymeleaf and the rest by angularjs
So i used a #Controller to forward all invalid url to the localhost:8080/:
#Controller
public class AccueilController {
// Match everything without a suffix (so not a static resource)
#RequestMapping(value = "/{path:[^\\.]*}")
public String redirect() {
// Forward to home page so that route is preserved.
return "forward:/";
}
}
when connecting if I type localhost:8080/XXXXthat forward me to the racine after login but if I type localhost:8080/XXXX/XXXX that give me a 404 error
after connection I don't have that problem because Angular forward all url correctly.
That's not the default behavior of the web applications. I sugest you to customize the not found page (Spring Boot and custom 404 error page) and then from there create a link to your home;

Spring MVC AngularJS No mapping found

I've been following the tutorial for integrating Spring Security with AngularJS, but it uses Spring Boot. I can get the tutorial examples working, but I need my app to run as a regular MVC application under Tomcat.
The problem is getting the application to route to the index.html page for the initial view. The only mappings I have in the controllers are the REST calls I want to receive from Angular, but I can't seem to get the application to go to the index page. Spring Boot does this automatically, but I'm going to run this as a web app under Tomcat. Trying to go there directly causes a 'No mapping found' error.
I'm using Java configuration and have the antMatchers, etc as described in the tutorial.
Here are a few entries in my config classes to make this happen.
#Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/index.html", "/home.html", "/login.html", "/").permitAll()
.antMatchers("/css/**").permitAll()
.antMatchers("/js/**").permitAll()
.antMatchers(HttpMethod.POST, "/user").permitAll().anyRequest()
.authenticated().and()
.csrf()
.csrfTokenRepository(csrfTokenRepository()).and()
.addFilterAfter(csrfHeaderFilter(), CsrfFilter.class);
if ("true".equals(System.getProperty("httpsOnly"))) {
LOGGER.info("launching the application in HTTPS-only mode");
http.requiresChannel().anyRequest().requiresSecure();
}
}
#Configuration
#EnableWebMvc
#ComponentScan("com.mygroupnotifier.controller")
public class ServletContextConfig extends WebMvcConfigurerAdapter {
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/css/**").addResourceLocations("/resources/static/css/");
registry.addResourceHandler("/js/**").addResourceLocations("/resources/static/js/");
registry.addResourceHandler("/*.html").addResourceLocations("/resources/static/");
}
#Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/").setViewName("forward:/index.html");
}
}
As usual the most difficult part of this is getting the leading and ending / on the classes and the html files.

Weld CDI on Google App Engine: Injection in servlet not happening

This is my first time working with GAE and I'm trying to get CDI working. Long story short: The #Inject field in my servlet is not getting injected (it's always null).
I'm working in Eclipse and debug the application on the local test server included in the GAE SDK (which is started by Eclipse as well). When I access the servlet on localhost, I get a null-pointer exception for someService. I've also output the value of someService to verify it is really null, which it is.
Edit: When I added a #Named("skldjfx") qualifier to the injection point, Weld complained the dependency is unsatisfied (in the validation phase), so that's a good sign. However, the field is still always null.
Servlet:
public class BlogServlet extends HttpServlet {
#Inject private SomeService someService;
public void doGet(HttpServletRequest req, HttpServletResponse resp)
throws IOException {
resp.setContentType("text/plain");
resp.getWriter().println("Hello. " + someService.getSomeValue());
// \
// always null
}
}
SomeService class:
#ApplicationScoped
public class SomeService {
private String someValue = "some value";
public String getSomeValue() {
return someValue;
}
}
I've configured Weld's Listener in web.xml:
<listener>
<listener-class>org.jboss.weld.environment.servlet.Listener</listener-class>
</listener>
The listener is properly loaded because it logs its initialization message: org.jboss.weld.environment.servlet.Listener contextInitialized.
I've included (an empty) beans.xml in both war/WEB-INF and war/META-INF. I also tried it without META-INF. Maybe beans.xml isn't processed? Other contents in the WEB-INF folder (such as web.xml) are processed properly.
How can I verify if beans.xml is processed and/or fix SomeService not getting injected?
It looks like it's not possible to use CDI with GAE, because GAE's Jetty fork ignores jetty-web.xml, which is needed to specify the BeanManager. See this link and this link. Really strange GAE is not supporting the use of CDI.
Note that these links are really old, but so far I haven't found any evidence to the contrary.
Anyway, my next step will be to use Google's own dependency injection framework Guice. Using it with GAE is described here. I'd prefer CDI though.

Resources