Skip to main content

Posts

Logging with logback

Greetings! It is important to add proper loggers into our application because when something bad happens, it is the way to gather related information. There are multiple libraries for logging in Java like JUL, log4j, logback. Spring uses logback as the default library. When we add any starter dependency that will add starter-logging as well since it depends transitively on the logging starter. howto-configure-logback-for-logging Complete source code,  todoapp $ git clone https://github.com/slmanju/todoapp.git $ cd todoapp $ gradle clean bootrun Log Levels Log messages can be used in several levels. ALL < DEBUG < INFO < WARN < ERROR < FATAL < OFF If WARN is enabled, then WARN, ERROR, FATAL will be logged Appenders Appenders responsible for writing log statements. ConsoleAppender – writes messages to the system console FileAppender – appends messages to a file RollingFileAppender – extends the FileAppender with the ability to roll over log fi...

REST tutorial : security with JWT token

Greetings! This is the last part of our security tutorial. Complete source code $ git clone https://github.com/slmanju/todoapp.git $ cd todoapp $ git checkout security follow the complete tutorial JWT JSON Web Token is an open standard that defines a compact and self-contained way for securely sharing data between parties using a JSON object. Compact - smaller size Self-contained - payload contains all the required information Typically contains, Header - consists of the type of the token, hashing algorithm being used Payload - contains the claims. Signature A token fields are separated by dots like this, xxx.yyy.zzz https://jwt.io/introduction/ Since we already have added token support in our previes tutorial, we only have to modify it to a JWT token. Sample Header {   "alg": "HS512" } Sample Payload {   "sub": "manjula",   "userId": "1",   "role": "ADMIN",   ...

REST tutorial : security

Greetings! So far we have created a nice looking REST API with Java tech stack. But it is missing a crucial piece. Security!!! Complete source code,  todoapp $ git clone https://github.com/slmanju/todoapp.git $ cd todoapp $ git checkout security Spring Security Spring Security is a powerful and highly customizable authentication and access-control framework. It is the de-facto standard for securing Spring-based applications. spring-security Lets add spring security starter to our project. compile('org.springframework.boot:spring-boot-starter-security') $ gradle clean bootrun $ curl -i http://localhost:8080/todos You will get a message like this, {"timestamp":1515304279482,"status":401,"error":"Unauthorized","message":"Full authentication is required to access this resource","path":"/todos"} With just adding the library Spring has secured our application! Have a look at the con...

REST tutorial : validations

Greetings! Our API is all good but it currently accepts empty Todos. Let's fix that with validations. You can find the complete source code here Todoapp Hibernate Validator Hibernate Validator allows to express and validate application constraints. Implements JSR 380 bean validation api. Hibernate validator is entirely separate from the persistence aspects of Hibernate. http://hibernate.org/validator/ Hibernate Validator 6.0 is the Reference Implementation of the Bean Validation 2.0 specification. Steps: Update gradle compile('javax.validation:validation-api:2.0.1.Final') compile('org.hibernate:hibernate-validator:6.0.7.Final') Update controller method to add @Valid check Update TodoDto with validators Catch validation exception in global exception handler (MethodArgumentNotValidException) Useful annotations @Length(min=, max=) - check if the string length match the range @Max(value=) - check if the value is less than or equals to max @Min(...

REST tutorial : error handling

Greetings! So far we have neglected error scenarios in our API. Any application without proper error handling is a disaster. You can find the complete source code here Todoapp Try these URLs and see the output. http://localhost:8080/todoss http://localhost:8080/todos/abcd Spring has handled errors for us!! but the messages are not interesting enough. Global exception handling With Spring's @ControllerAdvice we can handle exception globally.  ResponseEntityExceptionHandler : A convenient base class for @ControllerAdvice classes that wish to provide centralized exception handling across all @RequestMapping methods through @ExceptionHandler methods.  @RestControllerAdvice is a new feature of Spring Framework 4.3, an annotation with combined @ControllerAdvice + @ResponseBody Enable spring.mvc.throw-exception-if-no-handler-found to customize 404 error Note that our TodoService is also updated to throw a custom exception. See the complete code in error-...