I want to output userName if he log in.
From #Controller i have access:
#RequestMapping("/success")
public String success(Model model) {
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
String name = auth.getName(); //get logged in username
model.addAttribute("name", name);
return "success";
}
It work an if i use name on jsp, I see typed name.
But if in this jsp I write
<%# taglib prefix="sec" uri="http://www.springframework.org/security/tags" %>
<sec:authentication property="principal.username"/>
I get stackTrace:
INFO : com.epam.hhsystem.util.CustomAuthentificationProvider - User with name 'Nikolay_Tkachev' log in
07.08.2013 17:00:57 org.apache.jasper.compiler.TldLocationsCache tldScanJar
INFO: At least one JAR was scanned for TLDs yet contained no TLDs. Enable debug logging for this logger for a complete list of JARs that were scanned but no TLDs were found in them. Skipping unneeded JARs during scanning can improve startup time and JSP compilation time.
07.08.2013 17:00:57 org.apache.catalina.core.ApplicationDispatcher invoke
SEVERE: Servlet.service() for servlet jsp threw exception
org.springframework.beans.NotReadablePropertyException: Invalid property 'principal.username' of bean class [org.springframework.security.authentication.UsernamePasswordAuthenticationToken]: Bean property 'principal.username' is not readable or has an invalid getter method: Does the return type of the getter match the parameter type of the setter?
at org.springframework.beans.BeanWrapperImpl.getPropertyValue(BeanWrapperImpl.java:707)
at org.springframework.beans.BeanWrapperImpl.getPropertyValue(BeanWrapperImpl.java:699)
...
As you have authentiucation using using username and password, principal is it self the name of user. try using
<sec:authentication property="principal"/>
Related
Trying to read messages in consumer I get the following exception:
org.springframework.kafka.listener.ListenerExecutionFailedException: Listener failed; nested exception is org.springframework.kafka.support.serializer.DeserializationException: failed to deserialize; nested exception is org.springframework.messaging.converter.MessageConversionException: failed to resolve class name. Class not found
...
Caused by: org.springframework.messaging.converter.MessageConversionException: failed to resolve class name. Class not found
I've been looking at the deserialiser but I cannot seem to find the right way to resolve it.
I am working on an application split across different microservices.
Right now I am working on the logic to send emails to newly registered users. So for this scenario, I have two microservices; the user service and the email service.
User Management - Producer - application.yml
kafka:
properties:
security.protocol: 'PLAINTEXT'
template:
default-topic: user-creation
producer:
bootstrap-servers: ${kafka_bootstrap_servers:localhost:9092}
value-serializer: org.springframework.kafka.support.serializer.JsonSerializer
key-serializer: org.apache.kafka.common.serialization.StringSerializer
Email service - Consumer - application.yml
kafka:
properties:
security.protocol: 'PLAINTEXT'
consumer:
bootstrap-servers: ${kafka_bootstrap_servers:localhost:9092}
group-id: user-creation-consumer
auto-offset-reset: earliest
# Configures the Spring Kafka ErrorHandlingDeserializer that delegates to the 'real' deserializers
key-deserializer: org.springframework.kafka.support.serializer.ErrorHandlingDeserializer
value-deserializer: org.springframework.kafka.support.serializer.ErrorHandlingDeserializer
properties:
# Delegate deserializers
spring.json.trusted.packages: '*'
spring.deserializer.key.delegate.class: org.apache.kafka.common.serialization.StringDeserializer
spring.deserializer.value.delegate.class: org.springframework.kafka.support.serializer.JsonDeserializer
The user management service uses a Kafka topic user-creation to alert different microservices of user generation.
private final KafkaTemplate<String, RegisteredUser> kafkaTemplate;
public void sendMessage(RegisteredUser registeredUser){
log.info("########## Sending message: {}", registeredUser.toString());
this.kafkaTemplate.send(new ProducerRecord<>("user-creation", registeredUser));
}
The email service listens to the for updates on the user-creation topic:
#KafkaListener(topics = "user-creation")
#Service
#Slf4j
public class Consumer {
#KafkaHandler
public void listen(String string){
log.info("Received String message {}", string);
}
#KafkaHandler
public void listen(ConsumerRecord<String, NewUser> record) {
log.info("Receive NewUser object {}", record.value());
}
#KafkaHandler(isDefault = true)
public void consume(#Payload Object data) {
log.info("received data='{}'", data);
}
}
The two services are split to avoid tight coupling; hence the object RegisteredUser DTO used in User creation is not accessible to the Email service or the other services. I am using a very similar class with the same signature and fields but that is still failing.
What is the best way to handle such a scenario? I am quite new to Kafka so I am not sure how to progress - most tutorials online have the producer and consumer in the same code base so the DTO can be easily shared.
The idea is that the RegisteredUser DTO has fields/elements useful for other services so it will include more data - I only need to read a part of it.
TIA
I am trying to display a List of items in JSON format. My code structure utilizing SpringBoot and JPA Repository on Server side:
Entity class
Repository class created
Service written (contains repository.findAll() function)
Controller class
Goal is to output the record set extracted from SQL database onto localhost:8080/api/getinspection.
I have added Gson dependency in my pom.xml and in my controller class added code to convert to JSON.
I get an error saying:
java.lang.UnsupportedOperationException: Attempted to serialize java.lang.Class: org.hibernate.proxy.HibernateProxy.
Forgot to register a type adapter?
I have researched on type adapter on stackoverflow and tried to implement the solution, but in vain. Please help.
Service class
public List<INSPCTN> getInspections() {
return inspctnRepository.findAll(); }
Controller Class
#Service
public class InspectionService {
#Autowired
INSPCTNRepository inspctnRepository;
#GetMapping(path="/getInspection", produces = "application/JSON")
public String getInspections() {
List<INSPCTN> list = inspectionService.getInspections();
Gson gson = new Gson();
String json = gson.toJson(list);
return json;
}
}
Expected result: List of records from the database in JSON format
Actual:
There was an unexpected error (type=Internal Server Error, status=500).
Attempted to serialize java.lang.Class: org.hibernate.proxy.HibernateProxy.
Forgot to register a type adapter?
I have a Spring controller annotated class which implements this method:
#RequestMapping(value = "/event/eventList", method = RequestMethod.GET)
public #ResponseBody List<Event> listEvents() {
System.out.println("############ LIST EVENTS ############");
List<Event> events = eventService.listAllEvents();
for(Event event : events) {
Hibernate.getClass(event);
System.out.println(event);
}
return events;
}
when I call the page (localhost:8080/myapp/event/eventList) from browser, the method will be called correctly i see all the logs and the events are printed correctly meaning the event list is not empty and valid, but I get the error:
GRAVE: Servlet.service() for servlet [dispatcher] in context with path [/myapp] threw exception [Request processing failed; nested exception is java.lang.UnsupportedOperationException: Attempted to serialize java.lang.Class: org.hibernate.proxy.HibernateProxy. Forgot to register a type adapter?] with root cause
java.lang.UnsupportedOperationException: Attempted to serialize java.lang.Class: org.hibernate.proxy.HibernateProxy. Forgot to register a type adapter?
It does not return any Json representation.
I changed the method to return a string like:
#RequestMapping(value = "/event/eventList", method = RequestMethod.GET)
public #ResponseBody String listEvents() {
return "{'pippo':1}";
}
In this case the browser show the string correctly.
did I miss something?
The exception is thrown by com.google.gson.internal.bind.TypeAdapters when GSON is trying to serialize variable 'events' to Json.
This happens, cause
eventService.listAllEvents()
returns not a list already containing all events, but hibernate proxy that will do that lazy, when the list is actually used.
GSON does not know how to serialize that proxy.
Hibernate.getClass should initialize the underlying object as a side effect.
You need to call it also for the List 'events' itself, not only for every single event. The List can be a hibernate proxy also.
You may find more info on that topic at
Could not serialize object cause of HibernateProxy
I followed instructions on this blog post trying to enable anonymous access for the home page and redirect to Google if accessing /Admin page using this authorization.json.
{
"routes": [
{
"path_prefix": "/",
"policies": { "unauthenticated_action": "AllowAnonymous" }
},
{
"path_prefix": "/Admin",
"policies": { "unauthenticated_action": "RedirectToLoginPage" }
}
]
}
When I access the home page # http://mysite.azurewebsites.net/ it always navigates me to login page. And after I login then post redirection I am getting following errors inside log streaming.
2016-12-02T04:30:44 PID[11016] Verbose [Routes(Preview)] Attempting to load configuration from 'D:\home\site\wwwroot\authorization.json'.
2016-12-02T04:30:44 PID[11016] Critical System.Runtime.Serialization.SerializationException: There was an error deserializing the object of type Microsoft.Azure.AppService.Routes.RoutesConfig. Encountered unexpected character 'ï'. ---> System.Xml.XmlException: Encountered unexpected character 'ï'.
at System.Xml.XmlExceptionHelper.ThrowXmlException(XmlDictionaryReader reader, XmlException exception)
at System.Runtime.Serialization.Json.XmlJsonReader.ReadAttributes()
at System.Runtime.Serialization.Json.XmlJsonReader.ReadNonExistentElementName(StringHandleConstStringType elementName)
at System.Runtime.Serialization.Json.XmlJsonReader.Read()
at System.Xml.XmlBaseReader.IsStartElement()
at System.Xml.XmlBaseReader.IsStartElement(XmlDictionaryString localName, XmlDictionaryString namespaceUri)
at System.Runtime.Serialization.XmlReaderDelegator.IsStartElement(XmlDictionaryString localname, XmlDictionaryString ns)
at System.Runtime.Serialization.XmlObjectSerializer.IsRootElement(XmlReaderDelegator reader, DataContract contract, XmlDictionaryString name, XmlDictionaryString ns)
at System.Runtime.Serialization.Json.DataContractJsonSerializer.InternalIsStartObject(XmlReaderDelegator reader)
at System.Runtime.Serialization.Json.DataContractJsonSerializer.InternalReadObject(XmlReaderDelegator xmlReader, Boolean verifyObjectName)
at System.Runtime.Serialization.XmlObjectSerializer.InternalReadObject(XmlReaderDelegator reader, Boolean verifyObjectName, DataContractResolver dataContractResolver)
at System.Runtime.Serialization.XmlObjectSerializer.ReadObjectHandleExceptions(XmlReaderDelegator reader, Boolean verifyObjectName, DataContractResolver dataContractResolver)
--- End of inner exception stack trace ---
at System.Runtime.Serialization.XmlObjectSerializer.ReadObjectHandleExceptions(XmlReaderDelegator reader, Boolean verifyObjectName, DataContractResolver dataContractResolver)
at System.Runtime.Serialization.Json.DataContractJsonSerializer.ReadObject(XmlDictionaryReader reader)
at System.Runtime.Serialization.Json.DataContractJsonSerializer.ReadObject(Stream stream)
at Microsoft.Azure.AppService.Authentication.ModuleUtils.DecodeJson[T](Stream jsonStream)
at Microsoft.Azure.AppService.Routes.RoutesConfig.TryLoadFromFile(String configFilePath, Func`2 deserializer, RoutesConfig& config)
at Microsoft.Azure.AppService.Routes.RoutesConfig.TryLoadFromJsonFile(String configFilePath, RoutesConfig& config)
at Microsoft.Azure.AppService.Routes.RoutesModule.TryLoadRoutesConfig(HttpContextBase context)
at Microsoft.Azure.AppService.Routes.RoutesModule.<OnPostAuthenticateRequestAsync>d__4.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.Azure.AppService.Authentication.HttpModuleDispatcher.<DispatchAsync>d__13.MoveNext()
2016-12-02T04:30:44 PID[11016] Information Sending response: 500.79 Internal Server Error
Additional details.
1. Re-started the site after publishing from visual studio as mentioned.
2. Those /Admin path I have inside AdminController.
3. The authorization.json is at the root of the site. If I navigate to PS D:\home\site\wwwroot> I am able to see the authorization.json file.
I don't know what I am getting wrong regarding the syntax of the file.
According to your description, I followed URL Authorization Rules and created the authorization.json in my Visual Studio. I could make it work as expected on my Azure Web App.
https://bruce-chen-001.azurewebsites.net/
https://bruce-chen-001.azurewebsites.net/admin/admin.html
I assumed that there be something wrong with your authorization.json file. I found a similar issue about Encountered unexpected character ‘ï’ error serializing JSON, you could refer to it.
Updated
Here is my authorization.json file:
Please make sure you have chosen Allow Anonymous requests (no action) under the “Action to take when request is not authenticated” in the Authentication/Authorization blade of your App Service on Azure Portal.
I'm trying to use Spring-Data-Couchbase.
I want to get List from findAll(Iterable) method.
I set view 'all' to my Production View.
But, I meet the exception.
How Can I use findAll(Iterable) method?
Below is a Sample Code and exception.
Document Class:
#Document
public class User {
#Id
private String id;
private String userSeq;
}
Repository Class :
public interface UserRepository extends CouchbaseRepository<User, String> {
}
Service Class:
//List<String> get the Same result & exception.
Set<String> friendSet = new HashSet<String>();
friendSet.add("User8");
friendSet.add("User6");
userRepository.findAll(friendSet)
Exception:
Caused by: java.util.concurrent.ExecutionException: OperationException: SERVER: bad_request Reason: invalid UTF-8 JSON: {{error,{2,"lexical error: invalid char in json text.\n"}},
"[User8, User6]"}
at com.couchbase.client.internal.HttpFuture.waitForAndCheckOperation(HttpFuture.java:98)
at com.couchbase.client.internal.HttpFuture.get(HttpFuture.java:82)
at com.couchbase.client.internal.HttpFuture.get(HttpFuture.java:72)
at com.couchbase.client.CouchbaseClient.query(CouchbaseClient.java:778)
... 66 more
Caused by: OperationException: SERVER: bad_request Reason: invalid UTF-8 JSON: {{error,{2,"lexical error: invalid char in json text.\n"}},
"[User8, User6]"}
at com.couchbase.client.protocol.views.NoDocsOperationImpl.parseError(NoDocsOperationImpl.java:110)
at com.couchbase.client.protocol.views.ViewOperationImpl.handleResponse(ViewOperationImpl.java:68)
at com.couchbase.client.http.HttpResponseCallback.completed(HttpResponseCallback.java:103)
at com.couchbase.client.http.HttpResponseCallback.completed(HttpResponseCallback.java:51)
at org.apache.http.concurrent.BasicFuture.completed(BasicFuture.java:115)
at org.apache.http.nio.protocol.HttpAsyncRequester$RequestExecutionCallback.completed(HttpAsyncRequester.java:376)
at org.apache.http.concurrent.BasicFuture.completed(BasicFuture.java:115)
at org.apache.http.nio.protocol.BasicAsyncClientExchangeHandler.responseCompleted(BasicAsyncClientExchangeHandler.java:179)
at org.apache.http.nio.protocol.HttpAsyncRequestExecutor.processResponse(HttpAsyncRequestExecutor.java:349)
at org.apache.http.nio.protocol.HttpAsyncRequestExecutor.inputReady(HttpAsyncRequestExecutor.java:236)
at org.apache.http.impl.nio.DefaultNHttpClientConnection.consumeInput(DefaultNHttpClientConnection.java:267)
at org.apache.http.impl.nio.DefaultHttpClientIODispatch.onInputReady(DefaultHttpClientIODispatch.java:165)
at org.apache.http.impl.nio.DefaultHttpClientIODispatch.onInputReady(DefaultHttpClientIODispatch.java:51)
at org.apache.http.impl.nio.reactor.AbstractIODispatch.inputReady(AbstractIODispatch.java:113)
at org.apache.http.impl.nio.reactor.BaseIOReactor.readable(BaseIOReactor.java:159)
at org.apache.http.impl.nio.reactor.AbstractIOReactor.processEvent(AbstractIOReactor.java:338)
at org.apache.http.impl.nio.reactor.AbstractIOReactor.processEvents(AbstractIOReactor.java:316)
at org.apache.http.impl.nio.reactor.AbstractIOReactor.execute(AbstractIOReactor.java:277)
at org.apache.http.impl.nio.reactor.BaseIOReactor.execute(BaseIOReactor.java:105)
at org.apache.http.impl.nio.reactor.AbstractMultiworkerIOReactor$Worker.run(AbstractMultiworkerIOReactor.java:584)
... 1 more
You have to quote the id:s before you call findAll(...).
Set<String> friendSet = new HashSet<String>();
friendSet.add("\"User8\"");
friendSet.add("\"User6\"");
If the id:s aren't quoted the keys parameter sent to the Couchbase server will look something like [User8, User6] which isn't valid JSON, hence the exception. Pretty surprising behaviour...