#Autowired: the annotation #Autowired is disallowed for this location [closed] - java

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 days ago.
Improve this question
I have a problem I want to inject a service in the successfulAuthentication function of Spring Secuirty.
I had an error at #Autowired: the annotation #Autowired is disallowed for this location.
JwtAuthentificationFilter.java:
I tried to put it outside the function protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain, Authentication authResult), but when I execute and do the /login I get an error:
java.lang.NullPointerException: Cannot invoke
"org.sid.secservice.sec.service.EmailService.sendVerificationCode(String,
String)" because "this.emailService" is null

Related

How to set a variable for Controller from HttpInterceptor? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 10 months ago.
Improve this question
I am building a Spring Boot application.
I like to set a variable for the Spring Boot application. This variable should be set in an HTTP interceptor. The reason I do this, this variable will store some ID, and this ID will be used in methods in every controller.
How can I achieve this?
You SET the variable in an HTTP interceptor?
So it's not a unique global variable, it's an ID that is different for every request? That's what request attributes are for:
#Component
public class MyInterceptor extends HandlerInterceptorAdapter {
public boolean preHandle(HttpServletRequest request,
HttpServletResponse response,
Object handler) throws Exception {
if(request.getMethod().matches(RequestMethod.OPTIONS.name())) {
return true;
}
request.setAttribute("MY_ID", generateId(...));
return true;
}
}
#Controller
public class SampleController {
#RequestMapping(...)
public String something(HttpServletRequest req, HttpServletResponse res){
System.out.println( req.getAttribute("MY_ID"));
}
}
Pass it as JVM args and use it using System.getProperty.
Use -Dspring-boot.run.arguments=--interceptor.enabled=true and keep a backup config in application.properties or using -Drun.arguments and access the property key directly in your interceptor

How do I configure a Spring web application to use a different authentication method per end point [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
I have a web application - built using Java, Spring and Spring Security - that needs to support two different methods of authentication. The difficulty I have is that I want to use one authentication method on one set of controller end-points and the other method on the remaining end-points.
This is a difficulty because all the documentation I've read about multiple authentication providers seems to assume that you want all the providers to apply to all the end-points and you iterate through the providers until you find one that will authenticate the user.
I'm using Java annotation-base configuration (as opposed to XML configuration). Here are a few of the approaches I've explored without success:
configuring a provider with a pattern matcher to limit the end-points it applies
configuring a provider to only be triggered for certain authentication types, eg. if Digest credentials are present, trigger the Digest-based authentication provider
Can anyone suggest what is the best way to go about this? Is one of the above methods the correct way (and I've simply got it wrong)? Or is there another preferred way?
(I'm aware I've provided no specific code to review for an issue. This is because I'm only after guidance about the appropriate way of doing things in Spring.)
I'm using Spring Boot 2.0. I don't know about the best way but here's a way that worked for me. I had to break it out into to separate configuration classes and the second configuration needed to have the #Order annotation on it.
For my particular case I needed some administrative REST methods secured by HTTP basic authentication (username/password), and the remaining REST methods needed to be secured by custom logic.
#Configuration
#EnableWebSecurity
public class TestSecurityConfig extends WebSecurityConfigurerAdapter {
#Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().anyRequest().permitAll();
// anything that is NOT /admin/**
RequestMatcher requestMatcher = new NegatedRequestMatcher(new AntPathRequestMatcher("/admin/**", "GET"));
// MyCustomFilter is my class that performs custom authentication logic
http.requestMatcher(requestMatcher)
.addFilterAfter(new MyCustomFilter(), BasicAuthenticationFilter.class);
}
#Order(1)
#Configuration
public static class AdminServiceConfiguration extends WebSecurityConfigurerAdapter {
#Override
protected void configure(HttpSecurity http) throws Exception {
//this time anything that IS /admin/**
http.requestMatchers()
.antMatchers("/admin/**").and()
.httpBasic().and()
.authorizeRequests().antMatchers("/admin/**").fullyAuthenticated();
}
#Override
protected void configure(AuthenticationManagerBuilder authBuilder) throws Exception {
authBuilder.inMemoryAuthentication()
.passwordEncoder(NoOpPasswordEncoder.getInstance())
.withUser("username")
.password("password")
.roles("ADMIN");
}
}
}

Getting response object of a servlet in its superclass [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
I call method1 of servlet1 from service() of servlet2. I want to throw sendError(5xx) from servlet1. But it needs the response object of servlet2 which I am not passing. Any other method to throw the HTTP status codes?
public class servlet2 extends servlet1{
public void service(HttpServletRequest request, HttpServletResponse response){
}
}
public abstract class servlet1 extends HTTPServlet{
public void init(ServletConfig config) throws ServletException {
}
public boolean method1()
{
return true;
}
}
If you invoke a custom method1 of servlet1, from servlet2, then the servlet1 don't act as a real Servlet, but as a normal object. In that case, the servlet1 don't have any HttpServletResponse to wich send an error.
The normal way to dispatch the control from one servlet to another, is using a RequestDispatcher. For example, execute this sentence from servlet2:
getServletContext().getNamedDispatcher("servlet1").forward(request, response);
In servlet1, you receive the request in the service method, with receive as a parameter an HttpServletResponse, which you can use to send the error.

How to get the I.P. Address of client that is hitting your webservice? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
The title pretty much says it all, I have written a REST webservice in Java using JAX-RS and Jersey, and I would like to extract the I.P. address of the client that hits it in my code. If I have a class like this:
#Path("/service")
public class Service {
#GET
public void doAction () {
// ...
}
}
What do I do from there?
P.s. I'm not asking for debugging help, I'm asking how I can retrieve the IP address of the client that connects to my web service. #ANyarThar provided a good answer.
How #Context HttpServletRequest as argument in your method,
#GET
public void doAction (#Context HttpServletRequest req) {
//then get ip address
String ipAddress = req.getRemoteHost();
}

Enable caching in Tomcat 6? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about a specific programming problem, a software algorithm, or software tools primarily used by programmers. If you believe the question would be on-topic on another Stack Exchange site, you can leave a comment to explain where the question may be able to be answered.
Closed 8 years ago.
Improve this question
I need to increase the page load speed. In google page speed I have this issue:
The following cacheable resources have a short freshness lifetime. Specify an expiration at least one week in the future for the following resources.
So I should add expiration date to header to force browser to cache static content in the page. Is there any solution for this?
I use tomcat 6.0.26.
One Solution using spring framework
You need to write a filter something similar to this one:
#WebFilter(dispatcherTypes = { YourDispatcherTypes }, urlPatterns = { "*.jsp","/yourresourcename/*", "oranyother"})
public class CacheHandlingFilter extends OncePerRequestFilter {
#Override
protected void doFilterInternal(final HttpServletRequest request, final HttpServletResponse response, final FilterChain filterChain)
throws ServletException, IOException {
HttpServletRequest httpReq = (HttpServletRequest) request;
HttpServletResponse httpResp = (HttpServletResponse) response;
if(httpReq.getRequestURI().contains("/yourresourcename/")) {
httpResp.setDateHeader("Expires", ProvideTimeForCacheHere);
httpResp.setHeader("Cache-Control", "public, max-age=" + ProvideTimeForCacheHere);
}
filterChain.doFilter(request, response);
}
}
If you want something to apply cache headers globally across your servlets you could use a Filter.
Tomcat 7 has an ExpiresFilter built in; for Tomcat 6 you could write your own, or use a third-party library, to perform the same task.

Categories