<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Arunvincily on Medium]]></title>
        <description><![CDATA[Stories by Arunvincily on Medium]]></description>
        <link>https://medium.com/@arunvincily?source=rss-def30e4d5280------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*CFktbXaX2lK8Y0l-</url>
            <title>Stories by Arunvincily on Medium</title>
            <link>https://medium.com/@arunvincily?source=rss-def30e4d5280------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 07:47:14 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@arunvincily/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Spring Security in a Spring Boot application]]></title>
            <link>https://medium.com/@arunvincily/spring-security-in-a-spring-boot-application-c876b2f2ade9?source=rss-def30e4d5280------2</link>
            <guid isPermaLink="false">https://medium.com/p/c876b2f2ade9</guid>
            <category><![CDATA[spring-security]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[login]]></category>
            <category><![CDATA[git-repo]]></category>
            <category><![CDATA[spring]]></category>
            <dc:creator><![CDATA[Arunvincily]]></dc:creator>
            <pubDate>Fri, 14 Mar 2025 12:35:44 GMT</pubDate>
            <atom:updated>2025-03-14T12:35:44.822Z</atom:updated>
            <content:encoded><![CDATA[<p>Here is a <strong>step-by-step guide to implementing Spring Security in a Spring Boot application</strong>, including a basic <strong>JWT-based login and authentication</strong> for REST APIs:</p><p>Step 1: Add Spring Security Dependencies</p><p>Add the following dependencies to your pom.xml for <strong>Maven</strong>:</p><pre>&lt;dependencies&gt;<br>    &lt;!-- Spring Boot Starter Web --&gt;<br>    &lt;dependency&gt;<br>        &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>        &lt;artifactId&gt;spring-boot-starter-web&lt;/artifactId&gt;<br>    &lt;/dependency&gt;<br><br>    &lt;!-- Spring Boot Starter Security --&gt;<br>    &lt;dependency&gt;<br>        &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>        &lt;artifactId&gt;spring-boot-starter-security&lt;/artifactId&gt;<br>    &lt;/dependency&gt;<br><br>    &lt;!-- JWT Token Library --&gt;<br>    &lt;dependency&gt;<br>        &lt;groupId&gt;io.jsonwebtoken&lt;/groupId&gt;<br>        &lt;artifactId&gt;jjwt&lt;/artifactId&gt;<br>        &lt;version&gt;0.9.1&lt;/version&gt;<br>    &lt;/dependency&gt;<br>&lt;/dependencies&gt;</pre><h3>Step 2: Create a Security Configuration Class</h3><p>Create a class that extends WebSecurityConfigurerAdapter (for Spring Boot 2.x) or using SecurityFilterChain (for Spring Boot 3.x).</p><h3>Example (Spring Boot 3.x — SecurityFilterChain approach):</h3><pre>@Configuration<br>@EnableWebSecurity<br>public class SecurityConfig {<br><br>    @Bean<br>    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {<br>        http<br>            .csrf().disable()<br>            .authorizeHttpRequests(auth -&gt; auth<br>                .requestMatchers(&quot;/api/auth/**&quot;).permitAll() // Allow authentication APIs<br>                .anyRequest().authenticated() // Secure other APIs<br>            )<br>            .sessionManagement(session -&gt; session.sessionCreationPolicy(SessionCreationPolicy.STATELESS)); // No session<br><br>        return http.build();<br>    }<br><br>    @Bean<br>    public PasswordEncoder passwordEncoder() {<br>        return new BCryptPasswordEncoder();<br>    }<br>}</pre><p>Step 3: Create JWT Utility Class</p><pre>import io.jsonwebtoken.Claims;<br>import io.jsonwebtoken.Jwts;<br>import io.jsonwebtoken.SignatureAlgorithm;<br>import org.springframework.stereotype.Component;<br>import java.util.Date;<br><br>@Component<br>public class JwtUtil {<br><br>    private final String SECRET_KEY = &quot;secret&quot;;<br><br>    public String generateToken(String username) {<br>        return Jwts.builder()<br>                .setSubject(username)<br>                .setIssuedAt(new Date(System.currentTimeMillis()))<br>                .setExpiration(new Date(System.currentTimeMillis() + 1000 * 60 * 60 * 10)) // 10 hours<br>                .signWith(SignatureAlgorithm.HS256, SECRET_KEY)<br>                .compact();<br>    }<br><br>    public String extractUsername(String token) {<br>        return extractClaims(token).getSubject();<br>    }<br><br>    public boolean isTokenValid(String token, String username) {<br>        return username.equals(extractUsername(token)) &amp;&amp; !isTokenExpired(token);<br>    }<br><br>    private boolean isTokenExpired(String token) {<br>        return extractClaims(token).getExpiration().before(new Date());<br>    }<br><br>    private Claims extractClaims(String token) {<br>        return Jwts.parser().setSigningKey(SECRET_KEY).parseClaimsJws(token).getBody();<br>    }<br>}</pre><p>Step 4: Create Custom UserDetailsService</p><pre>import org.springframework.security.core.userdetails.User;<br>import org.springframework.security.core.userdetails.UserDetails;<br>import org.springframework.security.core.userdetails.UserDetailsService;<br>import org.springframework.security.core.userdetails.UsernameNotFoundException;<br>import org.springframework.stereotype.Service;<br><br>import java.util.ArrayList;<br><br>@Service<br>public class CustomUserDetailsService implements UserDetailsService {<br><br>    @Override<br>    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {<br>        // Normally fetch user from DB, here we hardcode<br>        if (&quot;admin&quot;.equals(username)) {<br>            return new User(&quot;admin&quot;, new BCryptPasswordEncoder().encode(&quot;password&quot;), new ArrayList&lt;&gt;());<br>        } else {<br>            throw new UsernameNotFoundException(&quot;User not found&quot;);<br>        }<br>    }<br>}</pre><p>Step 5: JWT Authentication Filter</p><pre>import jakarta.servlet.FilterChain;<br>import jakarta.servlet.ServletException;<br>import jakarta.servlet.http.HttpServletRequest;<br>import jakarta.servlet.http.HttpServletResponse;<br>import org.springframework.beans.factory.annotation.Autowired;<br>import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;<br>import org.springframework.security.core.context.SecurityContextHolder;<br>import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;<br>import org.springframework.stereotype.Component;<br>import org.springframework.web.filter.OncePerRequestFilter;<br><br>import java.io.IOException;<br><br>@Component<br>public class JwtAuthFilter extends OncePerRequestFilter {<br><br>    @Autowired<br>    private JwtUtil jwtUtil;<br><br>    @Autowired<br>    private CustomUserDetailsService userDetailsService;<br><br>    @Override<br>    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)<br>            throws ServletException, IOException {<br><br>        final String authHeader = request.getHeader(&quot;Authorization&quot;);<br>        String username = null;<br>        String jwt = null;<br><br>        if (authHeader != null &amp;&amp; authHeader.startsWith(&quot;Bearer &quot;)) {<br>            jwt = authHeader.substring(7);<br>            username = jwtUtil.extractUsername(jwt);<br>        }<br><br>        if (username != null &amp;&amp; SecurityContextHolder.getContext().getAuthentication() == null) {<br>            var userDetails = userDetailsService.loadUserByUsername(username);<br>            if (jwtUtil.isTokenValid(jwt, userDetails.getUsername())) {<br>                var authToken = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());<br>                authToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));<br>                SecurityContextHolder.getContext().setAuthentication(authToken);<br>            }<br>        }<br><br>        filterChain.doFilter(request, response);<br>    }<br>}</pre><p>Step 6: Authentication Controller</p><pre>import org.springframework.beans.factory.annotation.Autowired;<br>import org.springframework.security.authentication.AuthenticationManager;<br>import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;<br>import org.springframework.security.core.Authentication;<br>import org.springframework.security.core.AuthenticationException;<br>import org.springframework.web.bind.annotation.*;<br><br>@RestController<br>@RequestMapping(&quot;/api/auth&quot;)<br>public class AuthController {<br><br>    @Autowired<br>    private JwtUtil jwtUtil;<br><br>    @Autowired<br>    private AuthenticationManager authenticationManager;<br><br>    @PostMapping(&quot;/login&quot;)<br>    public String login(@RequestBody AuthRequest authRequest) throws Exception {<br>        try {<br>            Authentication auth = authenticationManager.authenticate(<br>                    new UsernamePasswordAuthenticationToken(authRequest.getUsername(), authRequest.getPassword()));<br>        } catch (AuthenticationException e) {<br>            throw new Exception(&quot;Invalid username/password&quot;);<br>        }<br>        return jwtUtil.generateToken(authRequest.getUsername());<br>    }<br>}<br><br>class AuthRequest {<br>    private String username;<br>    private String password;<br>    // getters and setters<br>}</pre><p>Step 7: Register Authentication Manager (Spring Boot 3.x)</p><pre>@Bean<br>public AuthenticationManager authenticationManager(AuthenticationConfiguration config) throws Exception {<br>    return config.getAuthenticationManager();<br>}</pre><p>Step 8: Add JWT Filter in Security Chain</p><p>Update SecurityConfig to add JWT Filter:</p><pre>@Autowired<br>private JwtAuthFilter jwtAuthFilter;<br><br>@Bean<br>public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {<br>    http<br>        .csrf().disable()<br>        .authorizeHttpRequests(auth -&gt; auth<br>            .requestMatchers(&quot;/api/auth/**&quot;).permitAll()<br>            .anyRequest().authenticated()<br>        )<br>        .sessionManagement(session -&gt; session.sessionCreationPolicy(SessionCreationPolicy.STATELESS));<br><br>    http.addFilterBefore(jwtAuthFilter, UsernamePasswordAuthenticationFilter.class);<br>    <br>    return http.build();<br>}</pre><h3>Output Flow:</h3><ol><li><strong>Login API (</strong><strong>/api/auth/login)</strong> with username/password returns JWT token.</li><li>Use JWT in Authorization header Bearer &lt;token&gt; for other secured API requests.</li></ol><h3>🔑 Sample Request/Response:</h3><p><strong>Login Request:</strong></p><pre>POST /api/auth/login<br>{<br>  &quot;username&quot;: &quot;admin&quot;,<br>  &quot;password&quot;: &quot;password&quot;<br>}</pre><p><strong>Login Response:</strong></p><pre>{<br>  &quot;token&quot;: &quot;eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...&quot;<br>}</pre><p><strong>Authorized Request:</strong></p><pre>http</pre><pre>GET /api/protected<br>Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...</pre><h3>Summary:</h3><ul><li>Setup JWT-based security in Spring Boot.</li><li>Protect REST APIs using Spring Security.</li><li>Use AuthenticationManager, JwtUtil, and UserDetailsService.</li></ul><p><strong>GitHub Repo Structure (Sample)</strong></p><pre>springboot-jwt-security-demo/<br>│<br>├── src/main/java/com/example/demo/<br>│   ├── config/<br>│   │   └── SecurityConfig.java<br>│   ├── controller/<br>│   │   └── AuthController.java<br>│   ├── filter/<br>│   │   └── JwtAuthFilter.java<br>│   ├── service/<br>│   │   └── CustomUserDetailsService.java<br>│   ├── util/<br>│   │   └── JwtUtil.java<br>│   ├── DemoApplication.java<br>│   └── model/<br>│       └── AuthRequest.java<br>│<br>├── src/main/resources/<br>│   └── application.properties<br>│<br>└── pom.xml</pre><h3>Repo Features:</h3><ul><li>JWT Authentication for REST APIs.</li><li>BCrypt password encoding.</li><li>Stateless security (no session storage).</li><li>Secured &amp; public endpoints.</li></ul><p><strong>Setup &amp; Run Instructions (to include in README.md):</strong></p><pre>git clone https://github.com/yourusername/springboot-jwt-security-demo.git<br>cd springboot-jwt-security-demo<br>./mvnw spring-boot:run</pre><h3>Example:</h3><ul><li>POST /api/auth/login → Get JWT Token.</li><li>GET /api/secured-data → Pass token as Authorization: Bearer &lt;token&gt;.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c876b2f2ade9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Spring Boot CRUD backend for an Employee Management System]]></title>
            <link>https://medium.com/@arunvincily/spring-boot-crud-backend-for-an-employee-management-system-0f7d9bb65a63?source=rss-def30e4d5280------2</link>
            <guid isPermaLink="false">https://medium.com/p/0f7d9bb65a63</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[springboot-3]]></category>
            <category><![CDATA[employees]]></category>
            <category><![CDATA[entity]]></category>
            <dc:creator><![CDATA[Arunvincily]]></dc:creator>
            <pubDate>Fri, 14 Mar 2025 12:24:42 GMT</pubDate>
            <atom:updated>2025-03-14T12:24:42.125Z</atom:updated>
            <content:encoded><![CDATA[<ol><li><strong>pom.xml (Dependencies)</strong></li></ol><pre>&lt;project xmlns=&quot;http://maven.apache.org/POM/4.0.0&quot;<br>         xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot;<br>         xsi:schemaLocation=&quot;http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd&quot;&gt;<br>    &lt;modelVersion&gt;4.0.0&lt;/modelVersion&gt;<br>    &lt;groupId&gt;com.yourname&lt;/groupId&gt;<br>    &lt;artifactId&gt;employee-management&lt;/artifactId&gt;<br>    &lt;version&gt;1.0.0&lt;/version&gt;<br>    &lt;dependencies&gt;<br>        &lt;dependency&gt;<br>            &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>            &lt;artifactId&gt;spring-boot-starter-web&lt;/artifactId&gt;<br>        &lt;/dependency&gt;<br>        &lt;dependency&gt;<br>            &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>            &lt;artifactId&gt;spring-boot-starter-data-jpa&lt;/artifactId&gt;<br>        &lt;/dependency&gt;<br>        &lt;dependency&gt;<br>            &lt;groupId&gt;mysql&lt;/groupId&gt;<br>            &lt;artifactId&gt;mysql-connector-java&lt;/artifactId&gt;<br>        &lt;/dependency&gt;<br>        &lt;dependency&gt;<br>            &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>            &lt;artifactId&gt;spring-boot-starter-validation&lt;/artifactId&gt;<br>        &lt;/dependency&gt;<br>    &lt;/dependencies&gt;<br>&lt;/project&gt;</pre><p>2. <strong>application.properties</strong></p><pre>spring.datasource.url=jdbc:mysql://localhost:3306/ems_db<br>spring.datasource.username=root<br>spring.datasource.password=your_password<br>spring.jpa.hibernate.ddl-auto=update<br>spring.jpa.show-sql=true<br>server.port=8080</pre><p>3. <strong>Employee.java (Model/Entity)</strong></p><pre>package com.yourname.employeemanagement.model;<br><br>import jakarta.persistence.*;<br>import jakarta.validation.constraints.NotBlank;<br>import lombok.Getter;<br>import lombok.Setter;<br><br>@Entity<br>@Getter<br>@Setter<br>public class Employee {<br><br>    @Id<br>    @GeneratedValue(strategy = GenerationType.IDENTITY)<br>    private Long id;<br><br>    @NotBlank(message = &quot;Name is required&quot;)<br>    private String name;<br><br>    @NotBlank(message = &quot;Email is required&quot;)<br>    @Column(unique = true)<br>    private String email;<br><br>    @NotBlank(message = &quot;Position is required&quot;)<br>    private String position;<br>}</pre><p>4. <strong>EmployeeRepository.java (Repository)</strong></p><pre>package com.yourname.employeemanagement.repository;<br><br>import com.yourname.employeemanagement.model.Employee;<br>import org.springframework.data.jpa.repository.JpaRepository;<br><br>public interface EmployeeRepository extends JpaRepository&lt;Employee, Long&gt; {<br>}</pre><p>5. <strong>EmployeeService.java (Service Interface)</strong></p><pre>package com.yourname.employeemanagement.service;<br><br>import com.yourname.employeemanagement.model.Employee;<br><br>import java.util.List;<br><br>public interface EmployeeService {<br>    Employee createEmployee(Employee employee);<br>    List&lt;Employee&gt; getAllEmployees();<br>    Employee getEmployeeById(Long id);<br>    Employee updateEmployee(Long id, Employee employee);<br>    void deleteEmployee(Long id);<br>}</pre><p>6. <strong>EmployeeServiceImpl.java (Service Implementation)</strong></p><pre>package com.yourname.employeemanagement.service;<br><br>import com.yourname.employeemanagement.exception.ResourceNotFoundException;<br>import com.yourname.employeemanagement.model.Employee;<br>import com.yourname.employeemanagement.repository.EmployeeRepository;<br>import org.springframework.stereotype.Service;<br><br>import java.util.List;<br><br>@Service<br>public class EmployeeServiceImpl implements EmployeeService {<br><br>    private final EmployeeRepository repository;<br><br>    public EmployeeServiceImpl(EmployeeRepository repository) {<br>        this.repository = repository;<br>    }<br><br>    @Override<br>    public Employee createEmployee(Employee employee) {<br>        return repository.save(employee);<br>    }<br><br>    @Override<br>    public List&lt;Employee&gt; getAllEmployees() {<br>        return repository.findAll();<br>    }<br><br>    @Override<br>    public Employee getEmployeeById(Long id) {<br>        return repository.findById(id)<br>                .orElseThrow(() -&gt; new ResourceNotFoundException(&quot;Employee not found with id &quot; + id));<br>    }<br><br>    @Override<br>    public Employee updateEmployee(Long id, Employee employeeDetails) {<br>        Employee employee = getEmployeeById(id);<br>        employee.setName(employeeDetails.getName());<br>        employee.setEmail(employeeDetails.getEmail());<br>        employee.setPosition(employeeDetails.getPosition());<br>        return repository.save(employee);<br>    }<br><br>    @Override<br>    public void deleteEmployee(Long id) {<br>        Employee employee = getEmployeeById(id);<br>        repository.delete(employee);<br>    }<br>}</pre><p>7. <strong>EmployeeController.java (REST Controller)</strong></p><pre>package com.yourname.employeemanagement.controller;<br><br>import com.yourname.employeemanagement.model.Employee;<br>import com.yourname.employeemanagement.service.EmployeeService;<br>import jakarta.validation.Valid;<br>import org.springframework.http.ResponseEntity;<br>import org.springframework.web.bind.annotation.*;<br><br>import java.util.List;<br><br>@RestController<br>@RequestMapping(&quot;/api/employees&quot;)<br>public class EmployeeController {<br><br>    private final EmployeeService service;<br><br>    public EmployeeController(EmployeeService service) {<br>        this.service = service;<br>    }<br><br>    @PostMapping<br>    public ResponseEntity&lt;Employee&gt; createEmployee(@Valid @RequestBody Employee employee) {<br>        return ResponseEntity.ok(service.createEmployee(employee));<br>    }<br><br>    @GetMapping<br>    public ResponseEntity&lt;List&lt;Employee&gt;&gt; getAllEmployees() {<br>        return ResponseEntity.ok(service.getAllEmployees());<br>    }<br><br>    @GetMapping(&quot;/{id}&quot;)<br>    public ResponseEntity&lt;Employee&gt; getEmployeeById(@PathVariable Long id) {<br>        return ResponseEntity.ok(service.getEmployeeById(id));<br>    }<br><br>    @PutMapping(&quot;/{id}&quot;)<br>    public ResponseEntity&lt;Employee&gt; updateEmployee(@PathVariable Long id, @Valid @RequestBody Employee employee) {<br>        return ResponseEntity.ok(service.updateEmployee(id, employee));<br>    }<br><br>    @DeleteMapping(&quot;/{id}&quot;)<br>    public ResponseEntity&lt;Void&gt; deleteEmployee(@PathVariable Long id) {<br>        service.deleteEmployee(id);<br>        return ResponseEntity.noContent().build();<br>    }<br>}</pre><p>8. <strong>ResourceNotFoundException.java (Custom Exception)</strong></p><pre>package com.yourname.employeemanagement.exception;<br><br>public class ResourceNotFoundException extends RuntimeException {<br>    public ResourceNotFoundException(String message) {<br>        super(message);<br>    }<br>}</pre><p>9. <strong>GlobalExceptionHandler.java (Exception Handler)</strong></p><pre>package com.yourname.employeemanagement.exception;<br><br>import org.springframework.http.HttpStatus;<br>import org.springframework.http.ResponseEntity;<br>import org.springframework.web.bind.annotation.ControllerAdvice;<br>import org.springframework.web.bind.annotation.ExceptionHandler;<br><br>import java.util.HashMap;<br>import java.util.Map;<br><br>@ControllerAdvice<br>public class GlobalExceptionHandler {<br><br>    @ExceptionHandler(ResourceNotFoundException.class)<br>    public ResponseEntity&lt;Map&lt;String, String&gt;&gt; handleResourceNotFound(ResourceNotFoundException ex) {<br>        Map&lt;String, String&gt; error = new HashMap&lt;&gt;();<br>        error.put(&quot;error&quot;, ex.getMessage());<br>        return new ResponseEntity&lt;&gt;(error, HttpStatus.NOT_FOUND);<br>    }<br>}</pre><p>10. <strong>Main Class (Spring Boot Starter)</strong></p><pre>package com.yourname.employeemanagement;<br><br>import org.springframework.boot.SpringApplication;<br>import org.springframework.boot.autoconfigure.SpringBootApplication;<br><br>@SpringBootApplication<br>public class EmployeeManagementApplication {<br>    public static void main(String[] args) {<br>        SpringApplication.run(EmployeeManagementApplication.class, args);<br>    }<br>}</pre><h3>How to Run:</h3><ol><li>Create a <strong>MySQL database</strong> named ems_db.</li><li>Add your <strong>DB username &amp; password</strong> in application.properties.</li><li>Run mvn spring-boot:run or from your IDE.</li><li>Access API:</li></ol><ul><li>POST /api/employees - Add Employee.</li><li>GET /api/employees - Get All Employees.</li><li>GET /api/employees/{id} - Get Employee by ID.</li><li>PUT /api/employees/{id} - Update Employee.</li><li>DELETE /api/employees/{id} - Delete Employee.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0f7d9bb65a63" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[concatenate two lists using Java Stream]]></title>
            <link>https://medium.com/@arunvincily/concatenate-two-lists-using-java-stream-9dfd2393246d?source=rss-def30e4d5280------2</link>
            <guid isPermaLink="false">https://medium.com/p/9dfd2393246d</guid>
            <category><![CDATA[concatenate]]></category>
            <category><![CDATA[stream]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Arunvincily]]></dc:creator>
            <pubDate>Fri, 14 Mar 2025 12:15:50 GMT</pubDate>
            <atom:updated>2025-03-14T12:15:50.554Z</atom:updated>
            <content:encoded><![CDATA[<p>To <strong>concatenate two lists using Java Stream</strong>, you can use Stream.concat() method which combines two streams and then collect them into a single list.</p><pre>import java.util.Arrays;<br>import java.util.List;<br>import java.util.stream.Collectors;<br>import java.util.stream.Stream;<br><br>public class ConcatListsExample {<br>    public static void main(String[] args) {<br>        List&lt;String&gt; list1 = Arrays.asList(&quot;Apple&quot;, &quot;Banana&quot;, &quot;Cherry&quot;);<br>        List&lt;String&gt; list2 = Arrays.asList(&quot;Date&quot;, &quot;Elderberry&quot;, &quot;Fig&quot;);<br><br>        // Concatenate two lists using Stream<br>        List&lt;String&gt; combinedList = Stream.concat(list1.stream(), list2.stream())<br>                                         .collect(Collectors.toList());<br><br>        // Output the combined list<br>        System.out.println(combinedList);<br>    }<br>}</pre><p>Output:</p><p>[Apple, Banana, Cherry, Date, Elderberry, Fig]</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9dfd2393246d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Install Microsoft SQL Server 2019 & SSMS on Windows]]></title>
            <link>https://medium.com/@arunvincily/how-to-install-microsoft-sql-server-2019-ssms-on-windows-5e4d4efca08e?source=rss-def30e4d5280------2</link>
            <guid isPermaLink="false">https://medium.com/p/5e4d4efca08e</guid>
            <dc:creator><![CDATA[Arunvincily]]></dc:creator>
            <pubDate>Fri, 07 Mar 2025 11:29:35 GMT</pubDate>
            <atom:updated>2025-03-07T11:29:35.301Z</atom:updated>
            <content:encoded><![CDATA[<ul><li>Official Microsoft URL for SQL Server download — <a href="https://www.microsoft.com/en-in/download/details.aspx?id=101064">https://www.microsoft.com/en-us/sql-server/sql-server-downloads</a></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2sIJC78V2mes7_2G85hz1Q.png" /></figure><ul><li>Click Download. It should download the version 2019 Express of SQL file with the .exe extension like below</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/395/1*88o8ZhkZBQNlcjdW5RxDGw.png" /></figure><ul><li>Click the file and choose the Basic option</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/840/1*KGb09Ffo0BdYRxWUOc1T7A.png" /></figure><ul><li>Next step accept the License Terms and Agreement, Later select the path where you want to install the software</li></ul><figure><img alt="Click install" src="https://cdn-images-1.medium.com/max/829/1*S4uVFkvYVVy6JQbMiTSkIA.png" /></figure><ul><li>Once the download and Installation has completed, click on the <strong>Connect Now</strong> button to test the connection (Highlighted below)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/832/1*FxpVGr4PQTPCifQ_exfFGw.png" /></figure><ul><li>After Clicking Connect Now, It should popup and show below prompt</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*0f2i7YBKPVhPP0RbrNFoRQ.png" /></figure><ul><li>After the above step, Go back to the previous window and click on <strong>Install SSMS </strong>(Highlighted Below)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/833/1*R7wPMSlx3rc2pp0ZGwxvNg.png" /></figure><ul><li>After clicking the option — <strong>Install SSMS,</strong> it will take you to Official Microsoft website — <a href="https://learn.microsoft.com/en-us/ssms/download-sql-server-management-studio-ssms?redirectedfrom=MSDN">https://learn.microsoft.com/en-us/sql/ssms/download-sql-server-management-studio-ssms?view=sql-server-ver16&amp;redirectedfrom=MSDN</a></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Cdd_TTr4ofrzeyDXKCrx2A.png" /></figure><ul><li>Scroll down on the above page and go to the below option, Click on the Free Download Link. It will download the latest version</li><li>But if you need the specific SQL Server Management Studio<strong> (SSMS) 2019</strong> version click the below link and it will download the file<br><a href="https://download.microsoft.com/download/7/7/3/7738e337-ed99-40ea-b8ae-f639162c83c3/SSMS-Setup-ENU.exe">https://download.microsoft.com/download/7/7/3/7738e337-ed99-40ea-b8ae-f639162c83c3/SSMS-Setup-ENU.exe</a></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/379/1*rC6ZpA2lpRmKdhUzP-KGRw.png" /></figure><ul><li>Click the .exe file once the download is completed and click on install (Below image)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/687/1*JNodMGWwduWlITtP381E8w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/645/1*K_33NgncGHaJCRydmqClNg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/644/1*aJSoNg4i08oYoxxbFJIgag.png" /></figure><ul><li>Once the application is installed, Click and open from your windows machine.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/659/1*7pWuFi7TSCLG5jLCwsImjA.png" /></figure><ul><li>Below Select as mentioned and click on Connect option</li></ul><p><strong>Server Type as — Database Engine</strong></p><p><strong>Server Name as — SQLEXPRESS </strong>(if you have multiple versions it will be like<strong> SQLEXPRESS01</strong>)</p><p><strong>Authentication as — Window Authentication</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xnvinkiKSo16ArJv2FiMxA.png" /></figure><ul><li>After Connect, the Below screen will appear. Then click on the <strong>New Query option</strong> to write an SQL Query</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JtUeG35BctLvOA-zeaq-cA.png" /></figure><ul><li>Below I have written and executed a query to print the list of databases present in the SQL Server — <em>SELECT name FROM sys.databases;</em></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*a1ychocG9aRwdzagY_utdg.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5e4d4efca08e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[OAuth2]]></title>
            <link>https://medium.com/@arunvincily/oauth2-03cd3a30dd17?source=rss-def30e4d5280------2</link>
            <guid isPermaLink="false">https://medium.com/p/03cd3a30dd17</guid>
            <category><![CDATA[spring-boot-oauth2]]></category>
            <dc:creator><![CDATA[Arunvincily]]></dc:creator>
            <pubDate>Tue, 30 Jul 2024 09:32:47 GMT</pubDate>
            <atom:updated>2024-07-30T09:32:47.511Z</atom:updated>
            <content:encoded><![CDATA[<p>OAuth2 is an authorization framework that enables the application Web Security to access the resources from the client. To build an OAuth2 application, we need to focus on the Grant Type (Authorization code), Client ID and Client secret.</p><h3>JWT Token</h3><p>JWT Token is a JSON Web Token, used to represent the claims secured between two parties. You can learn more about the JWT token at <a href="https://jwt.io/">www.jwt.io/</a>.</p><p>Now, we are going to build an OAuth2 application that enables the use of Authorization Server, Resource Server with the help of a JWT Token.</p><p>You can use the following steps to implement the Spring Boot Security with JWT token by accessing the database.</p><p>First, we need to add the following dependencies in our build configuration file.</p><p>Maven users can add the following dependencies in your pom.xml file.</p><pre>&lt;dependency&gt;<br>   &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>   &lt;artifactId&gt;spring-boot-starter-jdbc&lt;/artifactId&gt;<br>&lt;/dependency&gt;</pre><pre>&lt;dependency&gt;<br>   &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>   &lt;artifactId&gt;spring-boot-starter-security&lt;/artifactId&gt;<br>&lt;/dependency&gt;</pre><pre>&lt;dependency&gt;<br>   &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>   &lt;artifactId&gt;spring-boot-starter-web&lt;/artifactId&gt;<br>&lt;/dependency&gt;</pre><pre>&lt;dependency&gt;<br>   &lt;groupId&gt;org.springframework.security.oauth&lt;/groupId&gt;<br>   &lt;artifactId&gt;spring-security-oauth2&lt;/artifactId&gt;<br>&lt;/dependency&gt;</pre><pre>&lt;dependency&gt;<br>   &lt;groupId&gt;org.springframework.security&lt;/groupId&gt;<br>   &lt;artifactId&gt;spring-security-jwt&lt;/artifactId&gt;<br>&lt;/dependency&gt;</pre><pre>&lt;dependency&gt;<br>   &lt;groupId&gt;com.h2database&lt;/groupId&gt;<br>   &lt;artifactId&gt;h2&lt;/artifactId&gt;<br>&lt;/dependency&gt;</pre><pre>&lt;dependency&gt;<br>   &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>   &lt;artifactId&gt;spring-boot-starter-test&lt;/artifactId&gt;<br>   &lt;scope&gt;test&lt;/scope&gt;<br>&lt;/dependency&gt;</pre><pre>&lt;dependency&gt;<br>   &lt;groupId&gt;org.springframework.security&lt;/groupId&gt;<br>   &lt;artifactId&gt;spring-security-test&lt;/artifactId&gt;<br>   &lt;scope&gt;test&lt;/scope&gt;<br>&lt;/dependency&gt;</pre><p>Gradle users can add the following dependencies in the build.gradle file.</p><pre>compile(&#39;org.springframework.boot:spring-boot-starter-security&#39;)<br>compile(&#39;org.springframework.boot:spring-boot-starter-web&#39;)<br>testCompile(&#39;org.springframework.boot:spring-boot-starter-test&#39;)<br>testCompile(&#39;org.springframework.security:spring-security-test&#39;)</pre><pre>compile(&quot;org.springframework.security.oauth:spring-security-oauth2&quot;)<br>compile(&#39;org.springframework.security:spring-security-jwt&#39;)<br>compile(&quot;org.springframework.boot:spring-boot-starter-jdbc&quot;)<br>compile(&quot;com.h2database:h2:1.4.191&quot;)</pre><p>where,</p><ul><li><strong>Spring Boot Starter Security</strong> − Implements the Spring Security</li><li><strong>Spring Security OAuth2</strong> − Implements the OAUTH2 structure to enable the Authorization Server and Resource Server.</li><li><strong>Spring Security JWT</strong> − Generates the JWT Token for Web security</li><li><strong>Spring Boot Starter JDBC</strong> − Accesses the database to ensure the user is available or not.</li><li><strong>Spring Boot Starter Web</strong> − Writes HTTP endpoints.</li><li><strong>H2 Database</strong> − Stores the user information for authentication and authorization.</li></ul><p>The complete build configuration file is given below.</p><pre>&lt;?xml version = &quot;1.0&quot; encoding = &quot;UTF-8&quot;?&gt;<br>&lt;project xmlns = &quot;http://maven.apache.org/POM/4.0.0&quot; <br>   xmlns:xsi = &quot;http://www.w3.org/2001/XMLSchema-instance&quot;<br>   xsi:schemaLocation = &quot;http://maven.apache.org/POM/4.0.0 <br>   http://maven.apache.org/xsd/maven-4.0.0.xsd&quot;&gt;<br>   <br>   &lt;modelVersion&gt;4.0.0&lt;/modelVersion&gt;<br>   &lt;groupId&gt;com.tutorialspoint&lt;/groupId&gt;<br>   &lt;artifactId&gt;websecurityapp&lt;/artifactId&gt;<br>   &lt;version&gt;0.0.1-SNAPSHOT&lt;/version&gt;<br>   &lt;packaging&gt;jar&lt;/packaging&gt;<br>   &lt;name&gt;websecurityapp&lt;/name&gt;<br>   &lt;description&gt;Demo project for Spring Boot&lt;/description&gt;</pre><pre>   &lt;parent&gt;<br>      &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>      &lt;artifactId&gt;spring-boot-starter-parent&lt;/artifactId&gt;<br>      &lt;version&gt;1.5.9.RELEASE&lt;/version&gt;<br>      &lt;relativePath /&gt; &lt;!-- lookup parent from repository --&gt;<br>   &lt;/parent&gt;</pre><pre>   &lt;properties&gt;<br>      &lt;project.build.sourceEncoding&gt;UTF-8&lt;/project.build.sourceEncoding&gt;<br>      &lt;project.reporting.outputEncoding&gt;UTF-8&lt;/project.reporting.outputEncoding&gt;<br>      &lt;java.version&gt;1.8&lt;/java.version&gt;<br>   &lt;/properties&gt;</pre><pre>   &lt;dependencies&gt;<br>      &lt;dependency&gt;<br>         &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>         &lt;artifactId&gt;spring-boot-starter-jdbc&lt;/artifactId&gt;<br>      &lt;/dependency&gt;<br>      <br>      &lt;dependency&gt;<br>         &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>         &lt;artifactId&gt;spring-boot-starter-security&lt;/artifactId&gt;<br>      &lt;/dependency&gt;<br>      <br>      &lt;dependency&gt;<br>         &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>         &lt;artifactId&gt;spring-boot-starter-web&lt;/artifactId&gt;<br>      &lt;/dependency&gt;<br>      <br>      &lt;dependency&gt;<br>         &lt;groupId&gt;org.springframework.security.oauth&lt;/groupId&gt;<br>         &lt;artifactId&gt;spring-security-oauth2&lt;/artifactId&gt;<br>      &lt;/dependency&gt;<br>      <br>      &lt;dependency&gt;<br>         &lt;groupId&gt;org.springframework.security&lt;/groupId&gt;<br>         &lt;artifactId&gt;spring-security-jwt&lt;/artifactId&gt;<br>      &lt;/dependency&gt;<br>      <br>      &lt;dependency&gt;<br>         &lt;groupId&gt;com.h2database&lt;/groupId&gt;<br>         &lt;artifactId&gt;h2&lt;/artifactId&gt;<br>      &lt;/dependency&gt;<br>      <br>      &lt;dependency&gt;<br>         &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>         &lt;artifactId&gt;spring-boot-starter-test&lt;/artifactId&gt;<br>         &lt;scope&gt;test&lt;/scope&gt;<br>      &lt;/dependency&gt;<br>      <br>      &lt;dependency&gt;<br>         &lt;groupId&gt;org.springframework.security&lt;/groupId&gt;<br>         &lt;artifactId&gt;spring-security-test&lt;/artifactId&gt;<br>         &lt;scope&gt;test&lt;/scope&gt;<br>      &lt;/dependency&gt;<br>   &lt;/dependencies&gt;</pre><pre>   &lt;build&gt;<br>      &lt;plugins&gt;<br>         &lt;plugin&gt;<br>            &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>            &lt;artifactId&gt;spring-boot-maven-plugin&lt;/artifactId&gt;<br>         &lt;/plugin&gt;<br>      &lt;/plugins&gt;<br>   &lt;/build&gt;<br>   <br>&lt;/project&gt;</pre><p><strong>Gradle — build.gradle</strong></p><pre>buildscript {<br>   ext {<br>      springBootVersion = &#39;1.5.9.RELEASE&#39;<br>   }<br>   repositories {<br>      mavenCentral()<br>   }<br>   dependencies {<br>      classpath(&quot;org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}&quot;)<br>   }<br>}<br>apply plugin: &#39;java&#39;<br>apply plugin: &#39;eclipse&#39;<br>apply plugin: &#39;org.springframework.boot&#39;</pre><pre>group = &#39;com.tutorialspoint&#39;<br>version = &#39;0.0.1-SNAPSHOT&#39;<br>sourceCompatibility = 1.8</pre><pre>repositories {<br>   mavenCentral()<br>}</pre><pre>dependencies {<br>   compile(&#39;org.springframework.boot:spring-boot-starter-security&#39;)<br>   compile(&#39;org.springframework.boot:spring-boot-starter-web&#39;)<br>   testCompile(&#39;org.springframework.boot:spring-boot-starter-test&#39;)<br>   testCompile(&#39;org.springframework.security:spring-security-test&#39;)<br>   compile(&quot;org.springframework.security.oauth:spring-security-oauth2&quot;)<br>   compile(&#39;org.springframework.security:spring-security-jwt&#39;)<br>   compile(&quot;org.springframework.boot:spring-boot-starter-jdbc&quot;)<br>   compile(&quot;com.h2database:h2:1.4.191&quot;)  <br>}</pre><p>Now, in the main Spring Boot application, add the @EnableAuthorizationServer and @EnableResourceServer annotation to act as an Auth server and Resource Server in the same application.</p><p>Also, you can use the following code to write a simple HTTP endpoint to access the API with Spring Security by using JWT Token.</p><pre>package com.tutorialspoint.websecurityapp;</pre><pre>import org.springframework.boot.SpringApplication;<br>import org.springframework.boot.autoconfigure.SpringBootApplication;<br>import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;<br>import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;<br>import org.springframework.web.bind.annotation.RequestMapping;<br>import org.springframework.web.bind.annotation.RestController;</pre><pre>@SpringBootApplication<br>@EnableAuthorizationServer<br>@EnableResourceServer<br>@RestController<br>public class WebsecurityappApplication {<br>   public static void main(String[] args) {<br>      SpringApplication.run(WebsecurityappApplication.class, args);<br>   }<br>   @RequestMapping(value = &quot;/products&quot;)<br>   public String getProductName() {<br>      return &quot;Honey&quot;;   <br>   }<br>}</pre><p>Use the following code to define the POJO class to store the User information for authentication.</p><pre>package com.tutorialspoint.websecurityapp;</pre><pre>import java.util.ArrayList;<br>import java.util.Collection;<br>import org.springframework.security.core.GrantedAuthority;</pre><pre>public class UserEntity {<br>   private String username;<br>   private String password;<br>   private Collection&lt;GrantedAuthority&gt; grantedAuthoritiesList = new ArrayList&lt;&gt;();<br>   <br>   public String getPassword() {<br>      return password;<br>   }<br>   public void setPassword(String password) {<br>      this.password = password;<br>   }<br>   public Collection&lt;GrantedAuthority&gt; getGrantedAuthoritiesList() {<br>      return grantedAuthoritiesList;<br>   }<br>   public void setGrantedAuthoritiesList(Collection&lt;GrantedAuthority&gt; grantedAuthoritiesList) {<br>      this.grantedAuthoritiesList = grantedAuthoritiesList;<br>   }<br>   public String getUsername() {<br>      return username;<br>   }<br>   public void setUsername(String username) {<br>      this.username = username;<br>   }<br>}</pre><p>Now, use the following code and define the CustomUser class that extends the org.springframework.security.core.userdetails.User class for Spring Boot authentication.</p><pre>package com.tutorialspoint.websecurityapp;</pre><pre>import org.springframework.security.core.userdetails.User;</pre><pre>public class CustomUser extends User {<br>   private static final long serialVersionUID = 1L;<br>   public CustomUser(UserEntity user) {<br>      super(user.getUsername(), user.getPassword(), user.getGrantedAuthoritiesList());<br>   }<br>}</pre><p>You can create the @Repository class to read the User information from the database and send it to the Custom user service and also add the granted authority “ROLE_SYSTEMADMIN”.</p><pre>package com.tutorialspoint.websecurityapp;</pre><pre>import java.sql.ResultSet;<br>import java.util.ArrayList;<br>import java.util.Collection;<br>import java.util.List;</pre><pre>import org.springframework.beans.factory.annotation.Autowired;<br>import org.springframework.jdbc.core.JdbcTemplate;<br>import org.springframework.security.core.GrantedAuthority;<br>import org.springframework.security.core.authority.SimpleGrantedAuthority;<br>import org.springframework.stereotype.Repository;</pre><pre>@Repository<br>public class OAuthDao {<br>   @Autowired<br>   private JdbcTemplate jdbcTemplate;</pre><pre>   public UserEntity getUserDetails(String username) {<br>      Collection&lt;GrantedAuthority&gt; grantedAuthoritiesList = new ArrayList&lt;&gt;();<br>      String userSQLQuery = &quot;SELECT * FROM USERS WHERE USERNAME=?&quot;;<br>      List&lt;UserEntity&gt; list = jdbcTemplate.query(userSQLQuery, new String[] { username },<br>         (ResultSet rs, int rowNum) -&gt; {<br>         <br>         UserEntity user = new UserEntity();<br>         user.setUsername(username);<br>         user.setPassword(rs.getString(&quot;PASSWORD&quot;));<br>         return user;<br>      });<br>      if (list.size() &gt; 0) {<br>         GrantedAuthority grantedAuthority = new SimpleGrantedAuthority(&quot;ROLE_SYSTEMADMIN&quot;);<br>         grantedAuthoritiesList.add(grantedAuthority);<br>         list.get(0).setGrantedAuthoritiesList(grantedAuthoritiesList);<br>         return list.get(0);<br>      }<br>      return null;<br>   }<br>}</pre><p>You can create a Custom User detail service class that extends the org.springframework.security.core.userdetails.UserDetailsService to call the DAO repository class as shown.</p><pre>package com.tutorialspoint.websecurityapp;</pre><pre>import org.springframework.beans.factory.annotation.Autowired;<br>import org.springframework.security.core.userdetails.UserDetailsService;<br>import org.springframework.security.core.userdetails.UsernameNotFoundException;<br>import org.springframework.stereotype.Service;</pre><pre>@Service<br>public class CustomDetailsService implements UserDetailsService {<br>   @Autowired<br>   OAuthDao oauthDao;</pre><pre>   @Override<br>   public CustomUser loadUserByUsername(final String username) throws UsernameNotFoundException {<br>      UserEntity userEntity = null;<br>      try {<br>         userEntity = oauthDao.getUserDetails(username);<br>         CustomUser customUser = new CustomUser(userEntity);<br>         return customUser;<br>      } catch (Exception e) {<br>         e.printStackTrace();<br>         throw new UsernameNotFoundException(&quot;User &quot; + username + &quot; was not found in the database&quot;);<br>      }<br>   }<br>}</pre><p>Next, create a @configuration class to enable the Web Security, defining the Password encoder (BCryptPasswordEncoder), and defining the AuthenticationManager bean. The Security configuration class should extend WebSecurityConfigurerAdapter class.</p><pre>package com.tutorialspoint.websecurityapp;</pre><pre>import org.springframework.beans.factory.annotation.Autowired;<br>import org.springframework.context.annotation.Bean;<br>import org.springframework.context.annotation.Configuration;</pre><pre>import org.springframework.security.authentication.AuthenticationManager;<br>import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;<br>import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;<br>import org.springframework.security.config.annotation.web.builders.HttpSecurity;<br>import org.springframework.security.config.annotation.web.builders.WebSecurity;<br>import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;<br>import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;<br>import org.springframework.security.config.http.SessionCreationPolicy;<br>import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;<br>import org.springframework.security.crypto.password.PasswordEncoder;</pre><pre>@Configuration<br>@EnableWebSecurity<br>@EnableGlobalMethodSecurity(prePostEnabled = true)<br>public class SecurityConfiguration extends WebSecurityConfigurerAdapter {<br>   @Autowired<br>   private CustomDetailsService customDetailsService;</pre><pre>   @Bean<br>   public PasswordEncoder encoder() {<br>      return new BCryptPasswordEncoder();<br>   }<br>   @Override<br>   @Autowired<br>   protected void configure(AuthenticationManagerBuilder auth) throws Exception {<br>      auth.userDetailsService(customDetailsService).passwordEncoder(encoder());<br>   }<br>   @Override<br>   protected void configure(HttpSecurity http) throws Exception {<br>      http.authorizeRequests().anyRequest().authenticated().and().sessionManagement()<br>         .sessionCreationPolicy(SessionCreationPolicy.NEVER);<br>   }<br>   @Override<br>   public void configure(WebSecurity web) throws Exception {<br>      web.ignoring();<br>   }<br>   @Override<br>   @Bean<br>   public AuthenticationManager authenticationManagerBean() throws Exception {<br>      return super.authenticationManagerBean();<br>   }<br>}</pre><p>Now, define the OAuth2 Configuration class to add the Client ID, Client Secret, Define the JwtAccessTokenConverter, Private key and Public key for token signer key and verifier key, and configure the ClientDetailsServiceConfigurer for the Token validity with scopes.</p><pre>package com.tutorialspoint.websecurityapp;</pre><pre>import org.springframework.beans.factory.annotation.Autowired;<br>import org.springframework.beans.factory.annotation.Qualifier;<br>import org.springframework.context.annotation.Bean;<br>import org.springframework.context.annotation.Configuration;</pre><pre>import org.springframework.security.authentication.AuthenticationManager;<br>import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;<br>import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;<br>import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;<br>import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;<br>import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;<br>import org.springframework.security.oauth2.provider.token.store.JwtTokenStore;</pre><pre>@Configuration<br>public class OAuth2Config extends AuthorizationServerConfigurerAdapter {<br>   private String clientid = &quot;tutorialspoint&quot;;<br>   private String clientSecret = &quot;my-secret-key&quot;;<br>   private String privateKey = &quot;private key&quot;;<br>   private String publicKey = &quot;public key&quot;;</pre><pre>   @Autowired<br>   @Qualifier(&quot;authenticationManagerBean&quot;)<br>   private AuthenticationManager authenticationManager;<br>   <br>   @Bean<br>   public JwtAccessTokenConverter tokenEnhancer() {<br>      JwtAccessTokenConverter converter = new JwtAccessTokenConverter();<br>      converter.setSigningKey(privateKey);<br>      converter.setVerifierKey(publicKey);<br>      return converter;<br>   }<br>   @Bean<br>   public JwtTokenStore tokenStore() {<br>      return new JwtTokenStore(tokenEnhancer());<br>   }<br>   @Override<br>   public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {<br>      endpoints.authenticationManager(authenticationManager).tokenStore(tokenStore())<br>      .accessTokenConverter(tokenEnhancer());<br>   }<br>   @Override<br>   public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {<br>      security.tokenKeyAccess(&quot;permitAll()&quot;).checkTokenAccess(&quot;isAuthenticated()&quot;);<br>   }<br>   @Override<br>   public void configure(ClientDetailsServiceConfigurer clients) throws Exception {<br>      clients.inMemory().withClient(clientid).secret(clientSecret).scopes(&quot;read&quot;, &quot;write&quot;)<br>         .authorizedGrantTypes(&quot;password&quot;, &quot;refresh_token&quot;).accessTokenValiditySeconds(20000)<br>         .refreshTokenValiditySeconds(20000);</pre><pre>   }<br>}</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=03cd3a30dd17" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>